I just read about this and smacked myself on the forehead. Normally when developing an application I follow some sort of branding guidelines or perhaps make use of a custom font. I think most developer/designers DOI this quite regularly.
Now, I’ve found myself coding to those conventions over and over for various labels and like user interface controls. It’s a pain in the ass. If it needs to change you can search and replace in the project, or use messier methods. Not fun and prone to errors.
Extensions. We all use them too. However, they can be used to simplify your code and maintain consistency application-wide. You can put these in a separate Swift file to make them easier to track down.
/** Appearance .swift */ import UIKit extension UIColor { // Custom colours go here func custom() -> UIColor { return UIColor(red: 0.45, green: 0, blue: 0.95, alpha: 1) } } extension UIFont { // Custom fonts go here func custom(size:CGFloat) -> UIFont { return UIFont(name: "Avenir Next", size: size)! } }
I’ll reformat the above code soon, I’m on my phone at the moment. But look at that. It can be so simple to make edits to affect a great number of controls.
Here is an example implementation of the extension.
// Use the extensions from Appearance .swift label.textColor = UIColor().custom() label.font = UIFont().custom(size: 20)
How about using static variables? Excellent and clean!
import UIKit extension UIColor { // Static, computed variable for custom colour static var custom:UIColor { return UIColor(red: 0.45, green: 0, blue: 0.95, alpha: 1) } }
Now here is the implementation using a static variable.
label.textColor = .custom
Shazam. To me, this is really excellent. Easy to use, easy to modify, and it keeps your view controllers and the like slimmer and thus easier to read. No long lists of label modifications. You can take this concept quite far if you’d like to.