Customizing Search Bar Color
UI designers are always unsatisfied with default look of elements and trying to show own creativity through custom looking controls. And you as the person who in charge of implementing designs in code could be frustrated with difficulty and inflexibility of UIKit default controls. Here I want to share some tips and snippets for customizing UISearchBar objects.
Imagine the situation where your task is to make search bar match the application’s color scheme.
First of all, let’s review most obvious coloring options and realize it’s not obvious at all.
searchBar.backgroundColor = UIColor.green
At first, it seems that it did nothing, but if you have a good color perception or with a help of the Color Meter tool you can notice that desired color is blended with the default grayness of search bar.
Actually, it works as expected and changes view’s background color. But you can see it only through semitransparent bar view on top of it.
So how can you change this obstacle and get a solid background color for your search bar?
searchBar.barTintColor = UIColor.green
This code changes the color of this bar view so it’s no longer a problem.
What about the text field? There’s no property for its color. You need to create UISearchBar class extension like this:
Now with the single line of code, you can adjust the color of the text field.
As the extra touch lets try to change cursor color in text view mentioned above.
searchBar.tintColor = UIColor.green
What about icons?
You can access and customize magnifying glass icon with the following extension:
Placeholder text color is also customizable with similar code (but with value-for-key flavor):
That’s all for now. I’ll add more hints about UISearchBar here in case I forgot something. Have fun coding with Swift.