将 UIImage 图标与 UITextField 的居中占位符文本对齐的最佳方法是什么?前任:
我已经尝试复制这个有一段时间了,但似乎无法达到预期的效果。
我尝试过使用 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/