Wednesday, August 8, 2012

How to Control UISearchBar Background Color



When you have a list, you want to search it. How would you do that? No, don't code it by yourself. Done it, removed it.

By default each UITableView comes with search support via a built-in UISearchDisplayController. You just add and connect UISearchBar to your table in Interface Builder and provide some delegate methods to make it work. Pretty easy:
self.searchDisplayController.delegate =
self.searchDisplayController.searchBar.delegate =
self.searchDisplayController.searchResultsDataSource =
self.searchDisplayController.searchResultsDelegate = self.mySearchObject;
Controlling how your UISearchBar looks like is a bit more difficult. If you want to show search box and some other component(s) side by side, you can do it by putting UIToolbar at back and a short UISearchBar on top of it. By default their backgrounds are different, looking pretty ugly together. Like a hack, what it really is.

You can fix that by doing two things. First get rid of default background:
for (UIView *view in self.searchBar.subviews)
{
   if ([view isKindOfClass:NSClassFromString
     (@"UISearchBarBackground")])
   {
     [view removeFromSuperview];
     break;
   }
}
...and the second thing? Something that will be extremely hard to find out, unless you get it right by accident? You have to set UISearchBar style Black Translucent!

Sad to think how many hours I wasted experimenting Things That Will Not Work, just to find out that kind of miniscule solution. Also bet that this will not work one year from now...

4 comments: