4

How can I add a magnifying glass icon to the left of a UITextField?

I found an answer to a similar question here but I'm having trouble converting it to swift.

The answer:

So, here's the code with the unicode character:

UILabel *magnifyingGlass = [[UILabel alloc] init];
[magnifyingGlass setText:[[NSString alloc] initWithUTF8String:"\xF0\x9F\x94\x8D"]];
[magnifyingGlass sizeToFit];

[textField setLeftView:magnifyingGlass];
[textField setLeftViewMode:UITextFieldViewModeAlways];

Edit: For plain look that fits iOS 7 style, add Unicode variation selector \U000025B6.

My code:

let searchIconView = UILabel()
// Doesn't work: searchIconView.text = NSString.init(UTF8String: "\xF0\x9F\x94\x8D")
searchIconView.sizeToFit()
searchTextField.leftView = searchIconView
searchTextField.leftViewMode = .Always
Community
  • 1
  • 1
Code
  • 6,041
  • 4
  • 35
  • 75

4 Answers4

4

Do you have a specific reason for trying to add the icon as a UTF8String? If you have a magnifying glass icon as a PNG image, you can use the "leftView" property of UITextField like this;

let imageView = UIImageView()
let magnifyingGlassImage = UIImage(named: "magnifyingGlass")
imageView.image = magnifyingGlassImage
//arrange the frame according to your textfield height and image aspect
imageView.frame = CGRect(x: 0, y: 5, width: 45, height: 20)
imageView.contentMode = .ScaleAspectFit
txtField.leftViewMode = .Always
txtField.leftView = imageView
Batuhan C.
  • 384
  • 3
  • 10
3

In Swift you can assign emoji characters directly

searchIconView.text = ""
vadian
  • 274,689
  • 30
  • 353
  • 361
2

two simple approaches:

  1. You can use XCode to add Unicode symbols in your code directly (Edit->Emoji&Symbols).
  2. You can use something like that

    searchIconView.text = NSString(unicodeScalarLiteral: "\u{D83D}") as String

(you have to use your character here)

lithium
  • 1,272
  • 1
  • 14
  • 28
2

Updated for Swift 5 and using the System magnifying glass:

    let imageView = UIImageView()
    let magnifyingGlassImage = UIImage(systemName: "magnifyingglass", withConfiguration: UIImage.SymbolConfiguration(weight: .regular))?.withTintColor(.systemYellow, renderingMode: .alwaysOriginal)
    imageView.image = magnifyingGlassImage
    //arrange the frame according to your textfield height and image aspect
    imageView.frame = CGRect(x: 0, y: 5, width: 45, height: 20)
    imageView.contentMode = .scaleAspectFit
    txtField.leftViewMode = .always
    textField.leftView = imageView
Scooter
  • 4,068
  • 4
  • 32
  • 47