![](/img/trans.png)
[英]UItextfield in UIScrollView and move cursor with magnifying glass
[英]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 = "🔍"
兩種簡單的方法:
你可以使用類似的東西
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.