iOS状态栏颜色不改变的原因及设置

5 阅读1分钟

How to fix preferredStatusBarStyle not getting called

There are two common reasons that make the preferredStatusBarStyle property not getting called.

  • "View controller-based status bar appearance"(UIViewControllerBasedStatusBarAppearance) key set to NO in Info.plist
  • Your view controller is embedded in a ``UINavigationControllerorother Container View Controller`.

View controller-based status bar appearance key set to NO in Info.plist

If your project has the "View controller-based status bar appearance" key in the Info.plist, make sure it is set to "YES".

Having this flag set to "NO" tells the system to ignore whatever you set in preferredStatusBarStyle.

Embedded view controller

The preferredStatusBarStyle property won't get called if the view controller is embed in another container view controller, e.g., UINavigationController.

It doesn't get called because the one that gets called is its parent, UINavigationController.

This is because a parent view controller can have a custom view that covers the top part of the app, so it makes sense for the system to ask the parent view controller first.

A navigation view controller has a navigation bar that occupies the app's top part.

If you try subclass UINavigationController and override preferredStatusBarStyle, you can verify that the preferredStatusBarStyle in a MyNavigationController is the one getting called.

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

If you want a navigation controller to give control of the status bar style to its children, override the childForStatusBarStyle property and return any child view controllers that you want to determines the status bar style.

In this case, we return visibleViewController, which represents either the view controller at the top of the navigation stack or a view controller that was presented modally on top of the navigation controller itself.

class MyNavigationController: UINavigationController {
   override var childForStatusBarStyle: UIViewController? {
    return visibleViewController
    }
}

With this change, the preferredStatusBarStyle of your child view controllers will get called again.

link

sarunw.com/posts/prefe…