Topics

#263: Changing the Color of the Status Bar 🏴🏳

Topics

Today we're going to take a look at how to control how the status bar appears in our app. Let's get started.

The simplest way to change how the status bar looks in our app is to override preferredStatusBarStyle:

class SpaceshipViewController : UIViewController {
  override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
  }
}

The .lightContent style lives up to its name, as it makes the status bar's content white.

This work great until we put our view controller inside a navigation controller. Overriding the property then has no effect, as the system is actually asking the navigation controller.

We've all been here:

Yuck. Let's fix that up.

Since our content here is in a navigation controller we can use a "tried and true" approach that involves simply subclassing UINavigationController:

class LightStatusBarNavigationController : UINavigationController {
  override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
  }
}

To make this work, we can set this custom subclass in Interface Builder, or use it when creating our UI in code. Let's have a look now:

Nice.

This approach works in our case, but might not be the best way to do this. If the navigation bar ever gets hidden, UIKit will actually start asking the contained view controller for the status bar's style, which may or may not be what we want.

We could have accomplished the same thing using a plain old UINavigationController by simply setting its barStyle property when we create it (or by setting this property in Interface Builder) to the .blackOpaque style:

let nc = UINavigationController(rootViewController: spaceshipsVC)
navigationController?.navigationBar.barStyle = .blackOpaque

Or, even better, we could set this style using UINavigationBar's appearance proxy, so this style is applied to all the navigation bars in our app:

UINavigationBar.appearance().barStyle = .blackOpaque

(A huge hat tip to Caleb Davenport for helping out with these techniques!)

That takes care of the screens in our code, what about when the app first launches though?

For this, we'll need to turn to our project's settings.

Here we can hide and show the status bar during launch, and change its color. Let's take another look:

Perfect!