Configure UI Element’s Style

If we are making an app, it is likely that we would configure different styles for each UI element, such as font, background color. Here is how I would implement.

The reason why I write in this way is not because I want to have lazy initializations.

I prefer that each UI element has its own style configuration method. If the design changes in the future, we could easily locate and update it.

Putting style configuration into the getter method for the UI element has another benefit. If we put it into a different method, everyone on the team might come up with different names. Some may call it -configureAccessoryLabelAppearance. Others may call it -setupAccessoryLabel. Putting it inside the getter is consistent.

Pay attention. Do not add the UI element to its parent view in the getter.

Do not do it. Or it will bring uncertainty to your codes. For example, we want to have a label on top of an image view. If both the label and the image view are added to their parent view in the getters, which view will be on top when the app is running? It depends on the order that we call the corresponding properties. We need to access the image view first. It is an implicit constraint. Other people who read your code may not discover the constraint, and may break it when they make some changes. Do not add the UI element to its parent view in the getter. You can always add views like this:


You can get in touch with me via Twitter @guanshanliu.