带有包含图像和文本的占位符的 UITextField

Qua*_*ite 2 uitextfield swift

有什么办法可以让放大镜图标粘在 UITextField 中的占位符上,如下所示:

占位符旁边的搜索图标

我试图覆盖 leftViewRectForBounds(bounds: CGRect):

override func leftViewRectForBounds(bounds: CGRect) -> CGRect {
    var superRect = super.leftViewRectForBounds(bounds)
    superRect.origin.x += 80
    return superRect
  }
Run Code Online (Sandbox Code Playgroud)

但它没有用

Fog*_*ter 5

您可以使用NSAttributedString和将图像添加到文本中NSTextAttachment

我有一段时间没有使用它们了,但我相信你可以做这样的事情......

let magnifyingGlassAttachment = NSTextAttachment(data: nil, ofType: nil)
magnifyingGlassAttachment.image = UIImage(named: "MagnifyingGlass")

let magnifyingGlassString = NSAttributedString(attachment: magnifyingGlassAttachment)
Run Code Online (Sandbox Code Playgroud)

现在您可以使用magnifyingGlassString属性字符串并将其作为属性文本的一部分添加到UITextField.

我相信您还可以准确指定放大镜在字符串旁边的呈现方式(它如何包裹等......)

像这样的东西...

var attributedText = NSMutableAttributedString(attributedString: magnifyingGlassString)

let searchString = NSAttributedString(string: "Search for stuff")

attributedText.appendAttributedString(searchString)

textField.attributedPlaceholder = attributedText
Run Code Online (Sandbox Code Playgroud)