将C转换为Swift:将放大镜图标添加到UITextField

时间:2016-01-28 08:49:14

标签: ios swift

如何在UITextField左侧添加放大镜图标?

我找到了类似问题here的答案,但我无法将其转换为swift。

答案:

  

所以,这里是带有unicode字符的代码:

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

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

编辑:对于适合iOS 7风格的简单外观,添加Unicode变体选择器\ U000025B6。

我的代码:

let searchIconView = UILabel()
// Doesn't work: searchIconView.text = NSString.init(UTF8String: "\xF0\x9F\x94\x8D")
searchIconView.sizeToFit()
searchTextField.leftView = searchIconView
searchTextField.leftViewMode = .Always

4 个答案:

答案 0 :(得分:3)

您是否有特定原因尝试将图标添加为UTF8String?如果你有一个放大镜图标作为PNG图像,你可以使用" leftView"像这样的UITextField的属性;

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

答案 1 :(得分:3)

在Swift中,您可以直接指定表情符号字符

searchIconView.text = ""

答案 2 :(得分:2)

两种简单的方法:

  1. 您可以使用XCode直接在代码中添加Unicode符号(Edit-> Emoji& Symbols)。
  2. 你可以使用类似的东西

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

  3. (你必须在这里使用你的角色)

答案 3 :(得分:0)

针对 Swift 5 进行更新并使用系统放大镜:

    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