ios - NavigationBar 中的 UISearchBar 颜色
问题描述
我觉得我正在服用疯狂的药丸。我想更改 UISearchBar 中文本字段的颜色,该 UISearchBar 托管在 UINavigationBar 中。我遇到的问题是 UISearchBar 获取 UINavigationBar 的颜色,但 TextField 不会改变颜色。我在这里尝试了几种解决方案,但似乎都没有解决问题。任何想法如何更改 TextField 的颜色?
我知道还有其他与此类似的问题,但我已经尝试了我遇到的所有可能的解决方案,但还没有找到一个可以解决我的问题的解决方案。
当前代码:
let sc = UISearchController(searchResultsController: nil)
sc.delegate = self
let scb = sc.searchBar
scb.tintColor = UIColor.green
scb.barTintColor = UIColor.yellow
if let textfield = scb.value(forKey: "searchField") as? UITextField {
textfield.textColor = UIColor.blue
if let backgroundview = textfield.subviews.first {
// Background color
backgroundview.backgroundColor = UIColor.red
// Rounded corner
backgroundview.layer.cornerRadius = 5;
backgroundview.clipsToBounds = true;
}
}
navigationController?.navigationBar.barTintColor = UIColor.blue
navigationItem.searchController = sc
navigationItem.hidesSearchBarWhenScrolling = false
我创建了一个示例项目来展示它的实际效果。任何帮助或指导将不胜感激!
解决方案
如果您想在更多控制器中使用这些设置,也许最好的解决方案是为 UISearchBar 创建一个扩展。这里有一些例子。
extension UISearchBar {
private func getViewElement<T>(type: T.Type) -> T? {
let svs = subviews.flatMap { $0.subviews }
guard let element = (svs.filter { $0 is T }).first as? T else { return nil }
return element
}
func getSearchBarTextField() -> UITextField? {
return getViewElement(type: UITextField.self)
}
func setTextColor(color: UIColor) {
if let textField = getSearchBarTextField() {
textField.textColor = color
}
}
func setTextFieldColor(color: UIColor) {
if let textField = getViewElement(type: UITextField.self) {
switch searchBarStyle {
case .minimal:
textField.layer.backgroundColor = color.cgColor
textField.layer.cornerRadius = 6
case .prominent, .default:
textField.backgroundColor = color
@unknown default:
print("something")
}
}
}
func setPlaceholderTextColor(color: UIColor) {
if let textField = getSearchBarTextField() {
textField.attributedPlaceholder = NSAttributedString(string: self.placeholder != nil ? self.placeholder! : "", attributes: [NSAttributedString.Key.foregroundColor: color])
}
}
func setTextFieldClearButtonColor(color: UIColor) {
if let textField = getSearchBarTextField() {
let button = textField.value(forKey: "clearButton") as! UIButton
if let image = button.imageView?.image {
button.setImage(image.transform(withNewColor: color), for: .normal)
}
}
}
func setSearchImageColor(color: UIColor) {
if let imageView = getSearchBarTextField()?.leftView as? UIImageView {
imageView.image = imageView.image?.transform(withNewColor: color)
}
}
}
更新:
更改navigationItem.searchController = sc
为navigationItem.titleView = sc.searchBar
。
推荐阅读
- php - 为什么我得到一个非法的字符串偏移量?
- javascript - UnhandledPromiseRejectionWarning:CRA Universal 应用程序上出现未处理的承诺拒绝错误
- java - 错误:运算符不存在:bigint = 长空列表的字符变化
- python - 使用 Paramiko 连接到 SFTP 服务器失败并显示“需要整数(获取类型 str)”
- c - 创建 C 宏:连接字符串和数字
- rest - 如何在 Vue 3 中实现 PUT 请求
- python - 使用模型和委托小部件向 QTableView 添加行
- python - 将图像数组转换为浮点数时出现 ValueError
- c++ - 在 C++20 中使用 auto 转发参数?
- sql - 在计划任务中调用它时,雪花一个工作过程没有被成功执行