UISearchBar: changing the background color of the input field

I am trying to change the background color of a UISearchBar input field. In the rounded form, where you enter the text to search for, the default color is white. I would like to change it to gray

I tried:

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

But this does not work :(

I also tried pasting the image into a TextField, but it looks like the rounded view is separate from the TextField. So, any clues?

+7
ios objective-c iphone uisearchbar
Aug 29 2018-11-11T00:
source share
4 answers

Take a look at the function:

 [searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"search_bar"] forState:UIControlStateNormal]; 
+8
Oct 12
source share

=)

 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]]; } } } 
+8
May 08 '14 at 1:52
source share

In Swift 2 and iOS 9, you can call:

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

Swift 3:

 UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).backgroundColor = UIColor.darkGrey() 
+2
May 10 '16 at 5:30
source share

Solution in Swift 3:

 if let txfSearchField = searchController.searchBar.value(forKey: "_searchField") as? UITextField { txfSearchField.borderStyle = .none txfSearchField.backgroundColor = .lightGray } 
+2
Jun 04 '17 at 19:10
source share



All Articles