UISearchBar:改变input字段的背景颜色

我试图改变UISearchBar的input字段的背景颜色。它是您input要search的文本的圆angular视图,默认颜色是白色。 我想把它改成灰色

我试过了:

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

但它不工作:(

我也尝试插入一个图像视图到TextField,但它看起来圆angular的视图是独立于TextField。 那么,任何线索?

看function:

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

在Swift 2和iOS 9中,你可以调用:

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

Swift 3:

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

在Swift 3中的解决scheme:

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