I have a UISearchBar
contained within a UIView
and the UIView
has been assigned to a UITableView's tableHeaderView.
I'm trying to style the UISearchBar
to look like this:
Out of the gate, this is what it looks like:
There are loads of SO questions and answers on how to style UISearchBar
, its search field, etc., some with particular attention to backgrounds. Many of them involve traversing the UISearchBar's subviews
, finding a UISearchBarBackground
(or _UISearchBarSearchFieldBackgroundView
) object, and setting its background color directly. I'm trying to find a supported API for doing this, however...
The setSearchFieldBackgroundImage:forState:
method seems to have great potential, but this is what I get when I use a 1px white (or transparent) image using UIControlStateNormal
:
Any ideas as to how to get this to work? I'd appreciate someone pointing me to a SO post that answers this, but I really do think I've read them all. Thanks a ton.
you can use the appearanceWhenContainedIn to target elements without traversing the view hierarchy. Something like:
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setBackgroundColor:[UIColor whiteColor]];
[[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor lightGrayColor]];
UPDATE:
As appearanceWhenContainedIn
is now deprecated, use
[[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar self]]] <your setter here>];
I think the problem here is that when you use setSearchFieldBackgroundImage:forState:
, the height of your image actually determines the height of the search field. The standard search field (at least as of iOS 8) is 28 points tall, so an image that height should give the effect you're after.
(Somewhat confusingly, this also means that a nine-part stretchable image generally won't look right—so if you were going for a look that wasn't just white on white, you need to use a three-part stretchable image that only stretches horizontally.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With