我采用的是UISeachController

有以下几样自定义了

image-20200703232411687

取消按钮

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

背景颜色

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

文本颜色

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

Placeholder

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

放大镜颜色

1
2
3
4
5
6
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更为保险,目前我的方案:

1
2
3
4
5
6
7
8
9
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
}
}