简体   繁体   中英

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

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

在 Swift 中,您可以直接分配表情符号字符

searchIconView.text = "🔍"

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM