Jan
26
2012

Customize UISearchBar Background Image

In this post, I’ll walkthrough how to customize the background of UISearchBar.

In order to customize the UISearchBar, first we need to know it’s subviews. We can get the subviews by running the code below:

for (UIView *subview in [searchBar subviews]) {
        NSLog(@"%@", [subview class]);
}

If you run the code above, and you are running IOS 4.3 and above, you should see two subviews “UISearchBarBackground” and “UISearchBarTextField”. So, we know that UISearchBar consist of a background view and a textfield, that make sense.

default-uisearchbar

The default UISearchBar looks like the screenshot above, so let’s try to remove the background and see how the UISearchBar will look like by running the code below:

for (UIView *subview in [searchBar subviews]) {
    if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
    {
        [subview removeFromSuperview];
    }
}

The code is quite straight forward, it loop through all the subviews of UISearchBar and check if any subview belongs to the class “UISearchBarBackground”, if it is, remove it.

After you run the code, you should be able to see something like screenshot below. The background has been removed.

uisearchbar-without-background

Now we only left with the UITextfield, we can customize the UITexfield by running the code below:

for (UIView *subview in [searchBar subviews]) {
        if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
        {
            [subview removeFromSuperview];
        }
 
        if ([subview isKindOfClass:NSClassFromString(@"UISearchBarTextField")]) {
            [(UITextField *)subview setBackground:[UIImage imageNamed:@"searchboxbg.png"]];
        }
    }

The code above look for the UISearchBarTextField subview and set it’s background with our own image “searchboxbg.png”.

After running the code, you’ll see something like screenshot below.

custom-uisearchbar

This is how you can customize the UISearchBar.

About the Author:

Cayden is a programmer that expertize in ios and PHP development.

Leave a comment

Ads

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Facebook Page

Categories