Search code examples
iosobjective-ccustomizationuisearchbarbackground-color

How to change inside background color of UISearchBar component on iOS


I know how to remove/change UISearchBar 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+.


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.:

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

    I hope this help you...