ios - 居中 UITextField 占位符文本旁边的 UIImage

标签 ios swift uitextfield

将 UIImage 图标与 UITextField 的居中占位符文本对齐的最佳方法是什么?前任: http://imgur.com/a/Beqrt

我已经尝试复制这个有一段时间了,但似乎无法达到预期的效果。

我尝试过使用 UITextField 的 LeftView,但是无法将其与占位符文本对齐(我考虑通过更改其框架来向 LeftView 添加填充,但不确定如何获得对齐所需的值它位于占位符旁边。似乎无法获取占位符文本的坐标。)。我还尝试对 UITextField 进行子类化,但这里再次不确定如何获取正确的坐标。

最佳答案

您可以使用 NSTextAttachment 将图像附加到属性字符串内

swift 3.0

txtField.textAlignment = .center
let attachment = NSTextAttachment()
attachment.image = UIImage(named: "searchIcon")
attachment.bounds = CGRect(x: 0, y: 0, width: 10, height: 10)
let attachmentStr = NSAttributedString(attachment: attachment)
let myString = NSMutableAttributedString(string: "")
myString.append(attachmentStr)
let myString1 = NSMutableAttributedString(string: "Find a Location (Zip Code or Name)")
myString.append(myString1)
txtField.attributedPlaceholder = myString

Objective-C

NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [UIImage imageNamed:@"searchIcon"];
attachment.bounds = CGRectMake(0, 0, 10, 10);
NSAttributedString *attachmentStr = [NSAttributedString attributedStringWithAttachment:attachment];
NSMutableAttributedString *myString = [[NSMutableAttributedString alloc] initWithString:@""];
[myString appendAttributedString:attachmentStr];
NSMutableAttributedString *myString1 = [[NSMutableAttributedString alloc] initWithString:@"Find a Location (Zip Code or Name)"];
[myString appendAttributedString:myString1];
txtField.attributedPlaceholder = myString;

关于ios - 居中 UITextField 占位符文本旁边的 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42776826/

相关文章:

ios - 在 UITextField 中键入时保持占位符静态

ios - UILabel影响边界大小的行数

swift - 为什么我的合并管道中从未调用 sink ?

ios - 多个文本字段的键盘工具栏

ios - 在输入附件 View 中显示带有 UITextField 的键盘

Swift:如果计时器从函数启动,如何使计时器无效?

ios - 由于字体中的符号参数,切断了某些字体中的 UILabel 符号

javascript - Datepicker 在 ionic ios 中不起作用

ios - 如何在其他类的 ViewDidAppear 和 ViewDidDisappear 中插入代码

swift - Xcode 数组到 NSTableView