If you’re an iOS developer who doesn’t like to use storyboards and prefer to code (like me =) ), then you probably ended at some point with something like this:
What happens with this approach is that our code starts growing with a bunch of initialization code that makes our readability a lot more difficult. And, other than that, we start to replicate the same initialization logic over and over again instead of reusing it.
In this article I want to show you some simple, clean and light way to handle this type of initialization using the advantages that the Factory Pattern gives us.
The whole idea behind this pattern is to encapsulate the initialization logic into custom extensions so that the initialization code is cleaner.
Lets start by creating a static function into a new UILabel extension
By doing this we can already make some progress in our previous code:
We still need to add some initialization to this labels, for instance, setting the text and the color. This can be done in the ViewController’s viewDidLoad method. But, we can go one step ahead and do that in our static function that we just created.
Much better, right?
We still can go on and keep customizing our initialization function. For example, we can add the font that we want to set to our label. Let’s change our function:
As you can see, as we add parameters to our initialization function, our label definition starts losing legibility. But, don’t worry, we can improve our current implementation.
First, let’s think in the label’s font. In almost every app that we build, we have to follow some design standard. It’s highly probable that our title labels must have the same size, font type and color. Same for our subtitles and body labels. If you think about it, every UI component follow that similar pattern.
We can apply then the same concept for our custom fonts.
It’s also very probable that the color depend on the label type as well like the font. So, we can wrap that up in a custom enum that manages the label types logic.
Now, we can put all the pieces together and refactor to our initialization function.
Whit this implementation we can set up our labels using three different flavors:
- With a pre-define label type (like title, subtitle, etc.) and some text
- With no pre-define text at all (sometimes we just need to set up our label text latter)
- With no pre-define label type and some custom font.
The granularity of the customization will depend on your app needs, it can be bigger or it can be smaller. The one thing you need to keep in mind is that using this pattern will improve your code semantics, readability, and flexibility.