带有包含图像和文本的占位符的 UITextField [英] UITextField with a placeholder containing an image and text
问题描述
有什么办法可以让放大镜图标粘在 UITextField 中的占位符上,如下所示:
is there any way I could have a magnifier icon stuck to my placeholder in a UITextField like the below:
我试图覆盖 leftViewRectForBounds(bounds: CGRect):
override func leftViewRectForBounds(bounds: CGRect) -> CGRect {
var superRect = super.leftViewRectForBounds(bounds)
superRect.origin.x += 80
return superRect
}
但是没有用
推荐答案
您可以使用 NSAttributedString
和 NSTextAttachment
将图像添加到文本中.
You can add images to text using NSAttributedString
and NSTextAttachment
.
我已经有一段时间没有使用它们了,但我相信你可以做这样的事情......
I haven't used them in a while but I believe you can do something like this...
let magnifyingGlassAttachment = NSTextAttachment(data: nil, ofType: nil)
magnifyingGlassAttachment.image = UIImage(named: "MagnifyingGlass")
let magnifyingGlassString = NSAttributedString(attachment: magnifyingGlassAttachment)
现在您可以使用 magnifyingGlassString
属性字符串并将其作为属性文本的一部分添加到 UITextField
.
now you can use the magnifyingGlassString
attributed string and add it as part of the attributed text to the UITextField
.
我相信您还可以准确指定放大镜在字符串旁边的呈现方式(它如何包裹等...)
I believe you can also specify exactly how the magnifying glass renders alongside the string (how it wraps etc...)
这样的东西...
var attributedText = NSMutableAttributedString(attributedString: magnifyingGlassString)
let searchString = NSAttributedString(string: "Search for stuff")
attributedText.appendAttributedString(searchString)
textField.attributedPlaceholder = attributedText
这篇关于带有包含图像和文本的占位符的 UITextField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!