An experienced designer once told me that UI is more of a process than a fixed structure. It’s in constant flux. It is inconsistent by nature. And it’s complicated to make. So is UI the antithesis of clean and structured code?
An experienced iOS developer designs code that is easy to change. It means that if you need to change something that appears in multiple places within your app, it’s enough to modify one place in your code to fix them all. What tools do we have to make this happen?
First of all, we have UIAppearence which is an powerful tool but lacking in flexibility. It works best for UI elements that don’t have use more than one style, such as UINavigationBar or UITabBar. But if you need to change the color of your navigation bar with a single controller (some modal view, perhaps) you need to override this directly in UIViewController. Little-by-little your code will be crowded with these small hacks which make it painful to maintain and implement quickly. Also, this will likely lead to various bugs.
Since we know that UI elements in applications belong to groups with identical appearance (lets say all UISwitches) we can make some use of it. Probably, we can create a library of UI controls that are used within our application. UIButton sub-classes for similar buttons and reused related UITableViewCells. As long as you can do it without inheritance and complex hierarchies of classes it works fine. (You know that inheritance could be your worst nightmare, dont you?). But thats a lot of code.
So, the team at Intellectsoft decided to take some time to creating something which:
- Will allow us to use system classes (so we dont have to spread our attention too thin).
- Will require less code.
- Will be simple.
After spending some time with my colleague, we came up with the idea of applying styles for UI elements. Each system class would have a predefined set of styles and all you have to do within your UIViewController is to apply it. If we need to add another style it will not affect any other elements, and you can change styles in one place.
Lets dig into the code shall we?
As long as we are writing in Swift and following Apples advice on protocol-oriented programming, it’s natural that we start with a protocol.
Pretty simple. It only defines a function that performs styling. So we decided to add another protocol and extension to it with a default implementation. All UI elements that need to be styled (we dont have to style everything of cource) will adopt that protocol.
I hope this makes sense to you.
Here is an example of UILabel styling:
And using it in your code is quite simple and doesn’t take much time: