UIAppearance Tutorial: Getting Started

In this UIAppearance tutorial, you’ll learn how to make your app stand out by using Swift to customize the look and feel of standard UIKit controls. By Ron Kliffer.

Leave a rating/review
Save for later
Share
You are currently viewing page 4 of 4 of this article. Click here to view the first page.

Automating dark theme with Solar

For this part of the tutorial, you’ll use an open source library called Solar. Solar receives a location and date, and returns the sunrise and sunset times for that day. Solar comes installed with the starter project for this tutorial.

Note: For more on Solar, visit the library’s GitHub repository

Open AppDelegate.swift and add the following property below var window:

private let solar = Solar(latitude: 40.758899, longitude: -73.9873197)!

This defines a property of type Solar with today’s date and a given location. You can of course change the location so it’ll be taken dynamically according to the user’s location.

Still in AppDelegate, add the following two methods:

//1
func initializeTheme() {
  //2
  if solar.isDaytime {
    Theme.current.apply()
    scheduleThemeTimer()
  } else {
    Theme.dark.apply()
  }
}
  
func scheduleThemeTimer() {
  //3
  let timer = Timer(fire: solar.sunset!, interval: 0, repeats: false) { [weak self] _ in
    Theme.dark.apply()

    //4
    self?.window?.subviews.forEach({ (view: UIView) in
      view.removeFromSuperview()
      self?.window?.addSubview(view)
    })
  }

  //5
  RunLoop.main.add(timer, forMode: RunLoopMode.commonModes)
}

Let’s see what’s going on here:

  1. You define a method to initialize theme settings
  2. Solar has a convenience method to check if the time it was given is in daytime. If so, you apply the current theme and schedule a Timer that will change themes.
  3. You create a timer and set it to fire at sunset.
  4. This is an important thing to notice. Whenever UIAppearance changes values, they will not be reflected until the view re-renders itself. By removing and re-adding all the views to their window, you assure they are re-rendered according to the new theme.
  5. You schedule the timer by adding it to the main RunLoop

Finally, in application(_:didFinishLaunchingWithOptions:), replace:

Theme.current.apply()

with:

initializeTheme()

Open the app after sunset (You can change the time on your phone if you’re reading this during the day). The app should appear with dark theme selected.

Where to Go From Here?

You can download the finished project with all the tweaks from this tutorial here.

In addition to the tweaks you’ve already made, UIAppearance also supports customizing controls for a specific UITraitConnection. This let’s you support multiple themes for different device layouts.

I hope you enjoyed this UIAppearance tutorial and learned how easy it can be to tweak your UI. If you have any comments or questions about this tutorial, please join the forum discussion below!