Reputation: 6251
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
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
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
Reputation: 285072
In Swift you can assign emoji characters directly
searchIconView.text = "🔍"
Upvotes: 3
Reputation: 1302
two simple approaches:
You can use something like that
searchIconView.text = NSString(unicodeScalarLiteral: "\u{D83D}") as String
(you have to use your character here)
Upvotes: 2