UITextField with a placeholder containing an image and text

醉酒当歌 提交于 2019-12-14 02:35:44

问题


is there any way I could have a magnifier icon stuck to my placeholder in a UITextField like the below:

I tried to override leftViewRectForBounds(bounds: CGRect):

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

but it didn't work


回答1:


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)

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...)

Something like this...

var attributedText = NSMutableAttributedString(attributedString: magnifyingGlassString)

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

attributedText.appendAttributedString(searchString)

textField.attributedPlaceholder = attributedText



回答2:


You can add a image view or a custom view that displays this icon over the text field by properly placing it over and set up appropriate layout constraints. You will be adding this view as a sibling and not subview though.



来源:https://stackoverflow.com/questions/34897748/uitextfield-with-a-placeholder-containing-an-image-and-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!