[英]Convert C to Swift: Add magnifying glass icon to UITextField
How can I add a magnifying glass icon to the left of a UITextField
?如何在
UITextField
的左侧添加放大镜图标?
I found an answer to a similar question here but I'm having trouble converting it to swift.我在这里找到了一个类似问题的答案,但我无法将其转换为 swift。
The answer:答案:
So, here's the code with the unicode character:
所以,这是带有 unicode 字符的代码:
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.
编辑:对于适合 iOS 7 风格的简单外观,添加 Unicode 变体选择器 \\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?您是否有尝试将图标添加为 UTF8String 的特定原因? If you have a magnifying glass icon as a PNG image, you can use the "leftView" property of UITextField like this;
如果你有一个放大镜图标作为 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 = "🔍"
two simple approaches:两种简单的方法:
You can use something like that你可以使用类似的东西
searchIconView.text = NSString(unicodeScalarLiteral: "\\u{D83D}") as String 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:为 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.