我感觉自己像是疯了一样。我想要改变一个位于UINavigationBar中的UISearchBar中的textfield的颜色。问题在于,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
我创建了一个示例项目TestSearchBar来展示它的功能。非常感谢您的任何帮助或指导!
UISearchControllerDelegate
,但是你也添加了UISearchBarDelegate
吗? - DrisnavigationItem.searchController = sc
更改为navigationItem.titleView = sc.searchBar
,这对我有效。 - Dris