如何更改状态栏颜色?

时间:2020-09-23 13:34:40

标签: ios swift

在我的应用中,我将图像用作ViewController's的背景。对于项目设置中的状态栏,我设置为:Status Bar Style - Default。我没有在状态栏上使用其他任何东西。

问题是当启用iOS暗模式时,我的status bar变为白色。我需要它保持黑色。如何解决?

我也不想在应用程序中关闭iOS暗/亮模式支持。因此,Info.plist中的外观灯对我来说不太有用。

2 个答案:

答案 0 :(得分:2)

将状态栏样式设置为深色内容:

enter image description here

然后在您的info.plist中添加查看基于控制器的状态栏外观,并将其设置为

enter image description here

更新

如果您只想在确定的控制器中使用深色内容,请在viewWillAppear中添加setNeedsStatusBarAppearanceUpdate,然后重写preferredStatusBarStyle:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    setNeedsStatusBarAppearanceUpdate()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
    if #available(iOS 13.0, *) {
        return .darkContent
    } else {
        return .default
    }

从导航控制器开始:

在您的Scene委托中声明您的第一个导航控制器:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
    // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
    // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
    
    guard let windowScene = (scene as? UIWindowScene) else { return }
    window = UIWindow(windowScene: windowScene)
    window?.makeKeyAndVisible()
    let controller = UINavigationController(rootViewController: FirstViewController())
    controller.navigationBar.barStyle = .black
    window?.rootViewController = controller
}

在SecondViewController中覆盖状态栏样式

override var preferredStatusBarStyle: UIStatusBarStyle {
    if #available(iOS 13.0, *) {
        return .darkContent
    } else {
        return .default
    }
}

答案 1 :(得分:0)

对于每个ViewController,您都可以使用简单的覆盖方法设置状态栏颜色。

override var preferredStatusBarStyle: UIStatusBarStyle {
    if #available(iOS 13, *) {
        return .darkContent
    } else {
        return .default
    }
}

不要忘记在Info.plist中将基于控制器的视图状态栏外观设置为