UISearchBar:改变输入字段的背景颜色

问题描述:

我试图改变UISearchBar的输入字段的背景颜色。它是您输入要搜索的文本的圆角视图,默认颜色是白色。我想将它更改为灰色UISearchBar:改变输入字段的背景颜色

我想:

for (UIView *subView in searchBar.subviews) { 
    if ([subView isKindOfClass:NSClassFromString(@"UITextField")]) { 
     UITextField *textField = (UITextField *)subView; 
     [textField setBackgroundColor:[UIColor grayColor]]; 
    } 

但它不工作:(

我也试图插入的图像以文本字段,但它似乎圆形图从文本字段分开所以,任何线索

+0

ü应该在代码中创建搜索栏而不是在interfacebuilder.i中创建IB.so时出现同样的问题se代码创建搜索栏 –

+0

感谢您的回复。我会试试 – muc

+0

AHHHH,我做到了!我设置textField.background与图像,它的工作,耶! – muc

看功能:?

[searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"search_bar"] forState:UIControlStateNormal]; 

=)

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]]; 
     } 
    } 
} 

在夫特2和iOS 9可以调用:

UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).backgroundColor = UIColor.darkGrey() 

夫特3:

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).backgroundColor = UIColor.darkGrey() 
+1

Did not for me – SunilG

+2

如果'searchBarStyle'为'minimal',它将不起作用。 – enreas

+0

作为@enreas提到,解决方案是:http://stackoverflow.com/a/42626728/2229062 – yohannes

解在夫特3:

if let txfSearchField = searchController.searchBar.value(forKey: "_searchField") as? UITextField { 
     txfSearchField.borderStyle = .none 
     txfSearchField.backgroundColor = .lightGray 
}