Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing UISearchBar search field background

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:

What I want

Out of the gate, this is what it looks like:

How it looks now

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:

Using a transparent image for setSearchFieldBackgroundImage:forState:

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.

like image 895
Dave Avatar asked Nov 18 '13 05:11

Dave


2 Answers

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>];
like image 140
joneswah Avatar answered Sep 22 '22 09:09

joneswah


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.)

like image 24
robotspacer Avatar answered Sep 19 '22 09:09

robotspacer