Search code examples
iosswiftuiviewcontrolleruikitswift4

Swift 4 - Specific View Controller status bar style not changing


After implementing a UIViewController, it seems that the status bar content colour doesn't change (still remains black) for some reason. How can it be changed to the 'light' mode (white colour) programatically only using Swift 4.0 for just this specific UIViewController? Not the whole application.

ViewController.swift class

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()            
        view.backgroundColor = UIColor.blue

        self.title = "Hello World"
        self.navigationController?.navigationBar.barTintColor = UIColor.gray
        self.navigationController?.navigationBar.prefersLargeTitles = true
        self.navigationController?.navigationItem.largeTitleDisplayMode = .automatic

        self.navigationController?.navigationBar.largeTitleTextAttributes = [
            NSAttributedStringKey.foregroundColor: UIColor.white,
            NSAttributedStringKey.font : UIFont.preferredFont(forTextStyle: .largeTitle)
        ]
    }

    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
}

enter image description here

jake.lange's suggestion

enter image description here


Solution

  • Your UINavigationController is the one setting the preferredStatusBarColor. I bet if you tried presenting this VC instead of pushing it to the navigation controller you'd see the light statusbar style.

    What you'll probably want to do instead is implement a custom navigation controller and override preferred status bar style.

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

    EDIT:

    Based on comments what you're probably looking to do is set the preferred status bar color to whatever ViewController is the top most of the UINavigationController. Here's an extension that does that, with this extension you no longer need the CustomNavController class above, just used a regular UINavigationController. You will also need to override the preferred status bar style in each of your view controllers. Credit to this SO question, see here for more in depth discussions on statusbarstyle and navigation controllers: preferredStatusBarStyle isn't called

    extension UINavigationController {
        open override var childViewControllerForStatusBarStyle: UIViewController? {
            return self.topViewController
        }
    
        open override var childViewControllerForStatusBarHidden: UIViewController? {
            return self.topViewController
        }
    }