Search code examples
iosswiftcocoa-touchios9uistoryboard

Inherit background color and other attributes for many UIViewControllers


For an iOS9+/Swift 3 app with many UIViewControllers, what is the best practice way of inheriting the same background colors and other common attributes (fonts, spacing, etc...). Is it best to have a common base class? Or some sort of protocol?


Solution

  • Because most visual attributes are associated with specific UIViews and UIView subclasses (like UILabel, UIButton, etc.), I would suggest that having this handled at the UIViewController level is forcing the view controller to be responsible for too many details specific to other classes.

    Apple's built-in mechanism for setting global visual attributes on various views is the UIAppearance API. There's a good overview of that on NSHipster

    The downside of using UIAppearance is that is doesn't easily accommodate variations in styling, like some buttons being red and some buttons being blue. It's basically a fixed default appearance for all instances of a certain view across the app.

    I personally prefer using a dedicated styling framework that allows for applying combinations predefined styles to views. I have written about this and also created a framework to facilitate creating styles for UIKit components and applying and previewing them inside storyboards.