Borut Tomazin Borut Tomazin - 1 year ago 338
iOS Question

How to change inside background color of UISearchBar component on iOS

I know how to remove/change

background color around search field:

[[self.searchBar.subviews objectAtIndex:0] removeFromSuperview];
self.searchBar.backgroundColor = [UIColor grayColor];

achieved UISearchBar customization

But don't know how to do this inside it like that:

desired UISearchBar customization

This needs to be compatible with iOS 4.3+.


Answer Source

use this code for change the searchBar' 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"]];//just add here gray image which you display in quetion
    [searchField setBorderStyle:UITextBorderStyleNone];

This below code for change the UISearchBarIcon

 UIImageView *searchIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"yourSearchBarIconImage"]];
searchIcon.frame = CGRectMake(10, 10, 24, 24);
[searchBar addSubview:searchIcon];
[searchIcon release];

And Also For change the searcBar icon you can use inbuilt method of searchbar which available in iOS 5+,

- (void)setImage:(UIImage *)iconImage forSearchBarIcon:(UISearchBarIcon)icon state:(UIControlState)state

here you can set 4 types of UISearchBarIcon i.e.

  1. UISearchBarIconBookmark
  2. UISearchBarIconClear
  3. UISearchBarIconResultsList
  4. UISearchBarIconSearch

i hope this help you...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download