简体   繁体   中英

How to control the StatusBar style with code in Swift3.0

I use the code:

override var preferredStatusBarStyle: UIStatusBarStyle {
    return UIStatusBarStyle.lightContent
}

and I add

<key>UIViewControllerBasedStatusBarAppearance</key><false/>

in Info.plist.

But the StatusBar still is black style! Why?

SWIFT 3

UINavigationController overrides the view controller its preferred statusbar style. You can give control back to the view controller by subclassing the UINavigationController:

class BaseNavigationController: UINavigationController {

var statusBarStyle: UIStatusBarStyle?

override var preferredStatusBarStyle: UIStatusBarStyle {
    return statusBarStyle ?? .default
}

And then you're able to set the statusBarStyle property in the view controller:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    if let navigationController = navigationController as? BaseNavigationController {
        navigationController.statusBarStyle = preferredStatusBarStyle
    }
}

override var preferredStatusBarStyle: UIStatusBarStyle {
    return .default // any style you want
}

It's not working because in Info.plist you have specified <key>UIViewControllerBasedStatusBarAppearance</key><false/> . Change it that key to true , and it'll work. Main idea behind that key is, when it's true, application looks in your view controllers code for the status bar style for the implementation of preferredStatusBarStyle (for status bar style) and prefersStatusBarHidden (for if it should hide status bar for this view controller). And, when the UIViewControllerBasedStatusBarAppearance key is false, application looks for the global settings defined in General section of the target preferences (choose project file in project navigator in xcode).

Also, you have to keep in mind that, when your view controller is on containers like UINavigationController or UITabbarController , in order to change the status bar appearance, you have to extends those containers (write extension), and override preferredStatusBarStyle property.

You can check this answer on SO as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM