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

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

我在这里找到了一个类似问题的答案,但我很难将其转换为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 

两个简单的方法:

  1. 您可以使用XCode直接在代码中添加Unicode符号(编辑 – >表情符号和符号)。
  2. 你可以使用这样的东西

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

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

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

 searchIconView.text = "🔍" 

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

 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