Preferred status bar style

Need to change the preferredStatusBarStyle for one fo your child view controllers in your app? It might not be obvious on how to do it. This article explores one solution.

If you have a UINavigationController that is managing multiple UIViewController, you might be in a situation where you want to change the appearance of the UIStatusBarStyle per UIViewController in your stack.

In this situation, you can use an extension on the UINavigationController to help with this.

The key thing for this is the use of the word open. This allows you to modify it.


extension UINavigationController {   

    open override var preferredStatusBarStyle: UIStatusBarStyle {
        return topViewController?.preferredStatusBarStyle ?? .default
    }

}

Then in a UIViewController just state what you want.

class HomeCollectionViewController: UICollectionViewController {
    override var preferredStatusBarStyle: UIStatusBarStyle {
      return .lightContent
    }
}

open vs public

This is all about access control.

    open override var preferredStatusBarStyle: UIStatusBarStyle

An open class is accessible and subclassable outside of the defining module. An open class member is accessible and overridable outside of the defining module.

A public class is accessible but not subclassable outside of the defining module. A public class member is accessible but not overridable outside of the defining module.

Further reading

These two articles below help further put things into perspective. And go into the details and changes from Swift 3 to 4. Lots of details.

Source: What is the difference between public and open?
Source: What Is the Difference Between Public and Open in Swift 3