【问题标题】:Convert C to Swift: Add magnifying glass icon to UITextField将 C 转换为 Swift:向 UITextField 添加放大镜图标
【发布时间】:2016-05-05 13:06:43
【问题描述】:

如何在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

【问题讨论】:

    标签: ios swift


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      searchIconView.text = "?"
      

      【讨论】:

      • 我怎样才能得到这个图标的平面/普通版本? (就像 iOS 9 的默认设置)
      • 您可以使用任何 Unicode 字符。只需从字符面板中复制并粘贴即可。
      • @Code 请参阅下面的我的答案,以使用我相信您正在寻找的系统图标。
      【解决方案3】:

      两种简单的方法:

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

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

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

      【讨论】:

        【解决方案4】:

        为 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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-11-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-05-06
          • 2015-08-13
          相关资源
          最近更新 更多