enum RandomTips { case .appearance()

Table of Contents

Oops!

I seem to have forgotten to make posts the last couple days. In my defense, my in laws are visiting from out of town, so I’m doing everything I can to spend time with them and the wife, but that doesn’t excuse not sharing my learnings with you!

Neat!

Here’s some code inspired by what we learned yesterday:


enum AppearanceHelper {
    static let aColor = UIColor(red: 21/255, green: 17/255, blue: 16/255, alpha: 1)
    static let bColor = UIColor(red: 235/255, green: 170/255, blue: 42/255, alpha: 1)

    static setupAppearances() {
        UISegmentedControl.appearance().tintColor = bColor
        UINavigationBar.appearance().barTintColor = aColor
    }
}

Now we can call:

AppearanceHelper.setupAppearances() anywhere in our app to immediately set colors on all instances of segmented controls and navigation bars! If you want this done at the launch of your app, a smart place to put this call is in the AppDelegate didFinishLaunching.

There are a couple caveats/features

  • When you call these, it applies to every instance of the object type you call it on.
    • For example, if you set the background color of UIView, it’ll give EVERY UIView a background color, including subclasses (like UILabel)
    • use this to your advantage, not your defeat
  • You should be able to override these settings by setting values on individual objects following the setupAppearances call above
  • There are some elements that you can’t easily access here:
    • The navigation bar has title labels – we cannot edit those directly, but we CAN set attributes like this:
      let textAttributes = [NSAttributedString.Key.foregroundColor: bColor]
      UINavigationBar.appearance().titleTextAttributes = textAttributes
      UINavigationBar.appearance().largeTitleTextAttributes = textAttributes
    • There are other attributes we simply cannot set this way (or at least, we didn’t cover in class yesterday)

Basically this isn’t a solution for every color design problem, but it can go a long way to making it efficient to apply a color theme to your app!

Leave a Reply