Quantaliinuxite
Quantaliinuxite

Reputation: 3223

UITextField with a placeholder containing an image and text

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

Search Icon next to placeholder

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

Upvotes: 2

Views: 3105

Answers (2)

Fogmeister
Fogmeister

Reputation: 77641

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

Upvotes: 5

Shripada
Shripada

Reputation: 6524

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.

Upvotes: 1

Related Questions