The UIAppearance protocol is one of those handy, but under-utilized and under-documented features of UIKit for iOS developers.
Understanding how to use individual bits of UIAppearance is not hard, but figuring out how it behaves overall is a little more tricky.
Why Do This?
Designers love to fiddle with colors in apps, but if you’re not careful you end up with colors inserted all over the place in your apps, and little bits here and there become inconsistent - not to mention the difficulty of making changes in the future when color preferences change.
There are plenty of techniques for maintaining color consistency throughout your app, but the best code is the code you never write: the UIAppearance protocol helps you get it right, and does it easily.
With a few lines of code you can get the app color scheme just the way your designers want it, and you can send them off to work on more important things, like your app icon.
It takes one line of code to get a nice degree of UI color customization. To be specific
Objective-C (in your app delegate) self.window.tintColor = [UIColor orangeColor]; Swift (likewise) self.window?.tintColor = UIColor.orangeColor()
The lines will nicely tint the following objects throughout your app:
insertion and text selection in both cases
UITableView and allies
- UITableViewCell accessories
- UITableView sectionIndexColor
It will not tint some other objects though:
- UISearchBar (text, scope bar and buttons, not background)
Wait, Why Not This Way?
If you tint UIView either of these two ways:
Objective-C (in your app delegate) [UIWindow appearance].tintColor = [UIColor orangeColor]; or [UIView appearance].tintColor = [UIColor orangeColor]; Swift (likewise) UIView.appearance().tintColor = = UIColor.orangeColor() or UIWindow.appearance().tintColor = UIColor.orangeColor()
some of the items tinted by the window technique above remain untinted – in particular those that are not sub-classes of UIView.
The Advanced Stuff
We’ve posted an Xcode project for a demo app on Github here. The app uses Newton-like iterative methods to find the last valid values that can be formatted correctly.
The Demo App
We’ve posted an Xcode project for a demo app on Github here. The app shows how to use both the basic and the enhanced methods for creating a custom UI appearance. Just for fun, we wrote it in Swift.
What Not To Do
The standard Apple color scheme, which is black, white, and gray with a splash of “Apple Blue” for things you can tap
It’s probably not a good idea to repeatedly set UIAppearance protocol values - you will note that the sample app starts to slow down the more changes you make. Set your colors once when you start up, and then there should be no problems.