Code
Code

Reputation: 6251

Convert C to Swift: Add magnifying glass icon to UITextField

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

Upvotes: 4

Views: 2326

Answers (4)

Scooter
Scooter

Reputation: 4166

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

Upvotes: 3

Batuhan C.
Batuhan C.

Reputation: 380

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

Upvotes: 4

vadian
vadian

Reputation: 285072

In Swift you can assign emoji characters directly

searchIconView.text = "🔍"

Upvotes: 3

lithium
lithium

Reputation: 1302

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)

Upvotes: 2

Related Questions