avatar

UIKit-实现搜索框的自定义

我采用的是UISeachController

有以下几样自定义了

image-20200703232411687

取消按钮

UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).title = "取消"

背景颜色

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).backgroundColor = .white

文本颜色

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.orange]
//UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).textColor = .orange // 不起作用

Placeholder

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).attributedPlaceholder = NSAttributedString(string: "搜索个屁", attributes: [NSAttributedString.Key.foregroundColor: UIColor.yellow]) //颜色不起作用,但是对于普通UITextField起作用

放大镜颜色

if let textfield = searchController.searchBar.value(forKey: "searchField") as? UITextField {
if let leftView = textfield.leftView as? UIImageView {
leftView.image = leftView.image?.withRenderingMode(.alwaysTemplate)
leftView.tintColor = UIColor.red
}
}

补充

使用appearance方法时,如果重复入栈(重新打开页面)会失效,使用valueforkey更为保险,目前我的方案:

if let textfield = searchController.searchBar.value(forKey: "searchField") as? UITextField {
textfield.backgroundColor = .white
textfield.placeholder = "搜索"
textfield.attributedPlaceholder = NSAttributedString(string: "搜索", attributes: [NSAttributedString.Key.foregroundColor: UIColor.orange])
if let leftView = textfield.leftView as? UIImageView {
leftView.image = leftView.image?.withRenderingMode(.alwaysTemplate)
leftView.tintColor = TColor.main
}
}
文章作者: X Mεl0n
文章链接: http://www.zrzz.site/2020/07/03/UIKit-%E5%AE%9E%E7%8E%B0%E6%90%9C%E7%B4%A2%E6%A1%86%E7%9A%84%E8%87%AA%E5%AE%9A%E4%B9%89/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 X Mεl0n | 随手记

评论