繁体   English   中英

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

[英]Convert C to Swift: Add magnifying glass icon to 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

您是否有尝试将图标添加为 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

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

searchIconView.text = "🔍"

两种简单的方法:

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

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

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

为 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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