2

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

Peter Hornsby
  • 4,208
  • 1
  • 25
  • 44
Quantaliinuxite
  • 3,133
  • 4
  • 18
  • 32

2 Answers2

5

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
Fogmeister
  • 76,236
  • 42
  • 207
  • 306
  • this is a beautiful solution, is there any way the image could be centered with the rest of the text? – Quantaliinuxite Jan 20 '16 at 12:44
  • @Quantaliinuxite hi, yes you can do that by subclassing `NSTextAttachment` like is shown here... http://stackoverflow.com/questions/26105803/center-nstextattachment-image-next-to-single-line-uilabel – Fogmeister Jan 20 '16 at 12:46
  • I did see that, didn't think it was very elegant. Oh well! thanks :) – Quantaliinuxite Jan 20 '16 at 12:58
1

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.

Shripada
  • 6,296
  • 1
  • 30
  • 30
  • So would I calculate the size of the placeholder text, assume it's in the middle and simply place the icon there to the left of the calculated frame? – Quantaliinuxite Jan 20 '16 at 11:11
  • So this also works, it's a little more work than the other answer, but if more control of the positioning is needed this is a good method. I should add that it is much easier if the image view is added as a subview rather than a sibling. – Quantaliinuxite Jan 21 '16 at 11:06