Custom UISearchBar as a header view of UITableView in IB

If you add a UISearchBar to your UITableView in Interface Builder, it gives you a nice way to put the search bar as the header view of your table view, without any extra work involved such as creating the search bar in code and setting it up as a header view of the table. (OK, it is true that this is not that much more work, but I am super lazy.)

This works great if you want to use the search bar as is, without being able to customize it at all, which includes resizing it and adding additional controls to it.

My current needs dictated that I needed to add a bar code button to the right of the search bar that the user can use to scan in a bar code and kick off a search for the encoded data. I was going for the look of the search bar that is in the eBay iPhone app.

After many tries at subclassing UISearchBar and overriding drawRect and layoutSubviews in every perverted way possible, I stumbled on this Stack Overflow question and solution:

Changing the size of the UISearchBar TextField?

Basically, what you do here is to add a UIView to the table view instead of a UISearchBar. Then, you add a UINavigationBar to the UIView, and then resize it so that it only takes up a small portion of the view. After this, then you would add a UISearchBar to the empty space in your UIView, and then adjust the size of the UISearchBar to just fill up that empty space. (The navigation bar keeps the color gradient consistent across the header view.) And finally, you can then add any controls you want to the space that the small navigation bar occupies.

The only problem with this is that you have to manually manipulate the position of the new controls, as if you try to drag and drop, you might add the control as a UINavigationItem in the UINavigationBar.

On a conference note, I got tickets for myself and my co-workers to Stir Trek¬†(The Avengers Edition)¬†today a few minutes after they went on sale. Which is a good thing, as I understand they sold out in less than 15 minutes. I attended last year and had a good time, and I am hoping that this year’s edition has a better movie than last year’s Thor Edition. (Unfortunately, Thor does appear in The Avengers.)

BTW, happy Pi day everyone!

Leave a Reply