Xiaohao
Xiaohao

Reputation: 3

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?

Upvotes: 0

Views: 402

Answers (2)

Lloyd Keijzer
Lloyd Keijzer

Reputation: 1249

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
}

Upvotes: 4

Fahri Azimov
Fahri Azimov

Reputation: 11770

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.

Upvotes: 2

Related Questions