我正在尝试更改UISearchBar输入字段的背景颜色。这是您输入要搜索的文本的圆角视图,默认颜色为白色。我想把它改成灰色
我试过了:
for (UIView *subView in searchBar.subviews) {
if ([subView isKindOfClass:NSClassFromString(@"UITextField")]) {
UITextField *textField = (UITextField *)subView;
[textField setBackgroundColor:[UIColor grayColor]];
}
但它不起作用:(
我还尝试将图像视图插入TextField,但看起来圆角视图与TextField是分开的。那么,有什么线索吗?
答案 0 :(得分:9)
=)
for (UIView *subView in _searchBar.subviews) {
for(id field in subView.subviews){
if ([field isKindOfClass:[UITextField class]]) {
UITextField *textField = (UITextField *)field;
[textField setBackgroundColor:[UIColor grayColor]];
}
}
}
答案 1 :(得分:7)
查看功能:
[searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"search_bar"] forState:UIControlStateNormal];
答案 2 :(得分:3)
在Swift 2和iOS 9中,您可以致电:
UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).backgroundColor = UIColor.darkGrey()
斯威夫特3:
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).backgroundColor = UIColor.darkGrey()
答案 3 :(得分:3)
Swift 3中的解决方案:
if let txfSearchField = searchController.searchBar.value(forKey: "_searchField") as? UITextField {
txfSearchField.borderStyle = .none
txfSearchField.backgroundColor = .lightGray
}
答案 4 :(得分:0)
使扩展程序在swift4中起作用:
extension UISearchBar {
var input : UITextField? {
return findInputInSubviews(of: self)
}
func findInputInSubviews(of view: UIView) -> UITextField? {
guard view.subviews.count > 0 else { return nil }
for v in view.subviews {
if v.isKind(of: UITextField.self) {
return v as? UITextField
}
let sv = findInputInSubviews(of: v)
if sv != nil { return sv }
}
return nil
}
}
用法:
searchBar?.input?.layer.borderColor = color.cgColor