How to change inside background color of UISearchBar component on iOS
background-color, customization, ios, objective-c, uisearchbar
Solution
Use this code to change the searchBar's `UITextField` backgroundImage:
UITextField *searchField;
NSUInteger numViews = [searchBar.subviews count];
for (int i = 0; i < numViews; i++) {
if ([[searchBar.subviews objectAtIndex:i] isKindOfClass:[UITextField class]]) { //conform?
searchField = [searchBar.subviews objectAtIndex:i];
}
}
if (searchField) {
searchField.textColor = [UIColor whiteColor];
[searchField setBackground: [UIImage imageNamed:@"yourImage"]]; //set your gray background image here
[searchField setBorderStyle:UITextBorderStyleNone];
}
Use the below code to change the `UISearchBarIcon`:
UIImageView *searchIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"yourSearchBarIconImage"]];
searchIcon.frame = CGRectMake(10, 10, 24, 24);
[searchBar addSubview:searchIcon];
[searchIcon release];
Also, to change the searchBar icon you can use the following built-in method on `UISearchBar` (which is available from iOS 5+):
- (void)setImage:(UIImage *)iconImage forSearchBarIcon:(UISearchBarIcon)icon state:(UIControlState)state
Here you can set 4 types of `UISearchBarIcon` i.e.:
- `UISearchBarIconBookmark`
- `UISearchBarIconClear`
- `UISearchBarIconResultsList`
- `UISearchBarIconSearch`
I hope this help you...
Problem
I know how to remove/change `UISearchBar` background color around search field: ``` [[self.searchBar.subviews objectAtIndex:0] removeFromSuperview]; self.searchBar.backgroundColor = [UIColor grayColor]; ``` But don't know how to do this inside it like that: This needs to be compatible with iOS 4.3+.