我有一个搜索栏:
let searchBar:UISearchBar = UISearchBar(frame: CGRectMake((searchView.frame.width - UIScreen.mainScreen().bounds.width / 1.6) / 2, 0, UIScreen.mainScreen().bounds.width / 1.6, 24))
我想更改文本输入部分的背景颜色。为此我尝试过:
searchBar.barTintColor = UIColor(red: 0/255, green: 74/255, blue: 103/255, alpha: 1)
searchBar.backgroundColor = UIColor.redColor()
但这两种变体都不起作用。如何更改 UISearchBar textInput 部分的背景颜色以及我做错了什么?
就像@aliamcami一样,之前的所有答案都没有像我预期的那样工作,要么答案对我不起作用,要么它有效,但它需要太多“虚拟”代码。所以我分享另一个答案Swift 4简化逻辑:
for textField in searchController.searchBar.subviews.first!.subviews where textField is UITextField {
textField.subviews.first?.backgroundColor = .white
textField.subviews.first?.layer.cornerRadius = 10.5 //I set 10.5 because is approximately the system value
textField.subviews.first?.layer.masksToBounds = true
//Continue changing more properties...
}
textField.subviews.first
是“_UISearchBarSearchFieldBackgroundView”子视图,它在后面添加视觉效果UIFieldEditor
.
Edited
经过一些开发和许多错误后,我完成了这个elegant解决方案(我确信苹果不会乐意批准,但我不知道),适用于iOS 10 to iOS 12:
if let textField = searchBar.value(forKey: "searchField") as? UITextField {
textField.backgroundColor = myColor
//textField.font = myFont
//textField.textColor = myTextColor
//textField.tintColor = myTintColor
// And so on...
let backgroundView = textField.subviews.first
if #available(iOS 11.0, *) { // If `searchController` is in `navigationItem`
backgroundView?.backgroundColor = UIColor.white.withAlphaComponent(0.3) //Or any transparent color that matches with the `navigationBar color`
backgroundView?.subviews.forEach({ $0.removeFromSuperview() }) // Fixes an UI bug when searchBar appears or hides when scrolling
}
backgroundView?.layer.cornerRadius = 10.5
backgroundView?.layer.masksToBounds = true
//Continue changing more properties...
}
当。。。的时候searchBar
在里面tableHeaderView
上面的代码可以在中调用viewWillAppear
,但如果它在navigationItem
在 iOS 11 及更高版本上,应该调用它viewDidAppear
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)