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.
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.
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.
This is how you can customize the UISearchBar.
Leave a comment
Ads
Facebook Page
Categories
- Apache (1)
- Apps (2)
- Blog (19)
- IOS (20)
- IOS Library (5)
- iPhone Tutorial (17)
- Javascript (1)
- Node.js (1)
- Twitter (1)

An article by




