How to set the text color of the UISearchBar's

2019-05-21 10:11发布

问题:

I have a UISearchBar with a dark background color so I was trying to change the place holder text color of UISearchBar (which will be gray by default) but I didn't find a way to set it. So I thought of getting some help :) please suggest me how this can be achieved thanks in advance :)

回答1:

Note: At the time I wrote this answer I was working on iOS 7 & this workaround worked on iOS 8 as well. It may not work on iOS 9.

Ok it's been two days since I posted this question. Though I din't get the answer I got a workaround for this problem.

Note : I am using storyboard for my application & I have subclassed the UISearchBar and this workaround working like a gem for me.

First and foremost add an appearance proxy to UILabel when its contained in the UISearch bar class like this :

[[UILabel appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor whiteColor]];//change the color to whichever color needed

Then the most important thing is If you're using storyboard you must and should write some text in the placeholder field of the attribute inspector like this

If you forget to write something in the placeholder field, definitely this trick will not work when you run the application and the placeholder text will look in usual gray color.

Once you're done with writing some text in placeholder field, set the place holder text in your UISearchBar sub class like this :

self.placeholder = @"My Placeholder text";

Now run the application !!! You'll get the place holder text in the color which you have set in appdelegate:) Hope this helps someone :)



回答2:

Here is the solution

[searchBar setValue:[UIColor blueColor] forKeyPath:@"_searchField.textColor"];