有什么方法可以让我的占位符粘贴在UITextField中,如下所示:
我试图覆盖leftViewRectForBounds(bounds: CGRect):
override func leftViewRectForBounds(bounds: CGRect) -> CGRect {
var superRect = super.leftViewRectForBounds(bounds)
superRect.origin.x += 80
return superRect
}
但它无效
答案 0 :(得分:3)
您可以使用NSAttributedString
和NSTextAttachment
将文字添加到文字中。
我有一段时间没有使用它们,但我相信你可以做这样的事情......
let magnifyingGlassAttachment = NSTextAttachment(data: nil, ofType: nil)
magnifyingGlassAttachment.image = UIImage(named: "MagnifyingGlass")
let magnifyingGlassString = NSAttributedString(attachment: magnifyingGlassAttachment)
现在,您可以使用magnifyingGlassString
属性字符串,并将其作为属性文本的一部分添加到UITextField
。
我相信你也可以确切地说明放大镜如何在字符串旁边呈现(它是如何包裹的......)
像这样......
var attributedText = NSMutableAttributedString(attributedString: magnifyingGlassString)
let searchString = NSAttributedString(string: "Search for stuff")
attributedText.appendAttributedString(searchString)
textField.attributedPlaceholder = attributedText
答案 1 :(得分:1)
您可以添加图像视图或在文本字段上显示此图标的自定义视图,方法是将其正确放置并设置适当的布局约束。您将添加此视图作为兄弟而不是子视图。