简体   繁体   English

如何更改状态栏的外观?

[英]How can I change the appearance of the status bar?

I'm trying to change te appearance of here status bar based on Userdefaults, who detect if the user has the mode turned on, but using setNeedsStatusBarAppearanceUpdate() doesn't work.我正在尝试根据用户默认值更改此处状态栏的外观,用户默认值检测用户是否打开了该模式,但使用setNeedsStatusBarAppearanceUpdate()不起作用。 I set the default status bar as Light.我将默认状态栏设置为 Light。 This is the code that I'm currently using:这是我目前使用的代码:

var darkModeOn: Bool! 

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

    let isDarkMode = UserDefaults.standard.bool(forKey: "isDarkMode")  // Retrieve the state

    if isDarkMode == false{

        UserDefaults.standard.set(false, forKey: "isDarkMode")
        UIApplication.shared.statusBarStyle = .default
        view.backgroundColor = UIColor.white

    }else{

        UserDefaults.standard.set(true, forKey: "isDarkMode")
        UIApplication.shared.statusBarStyle = .lightContent
        view.backgroundColor = UIColor(red: 35/255, green: 35/255, blue: 35/255, alpha: 1)


    }

}

And I've tried to use我试过用

override var preferredStatusBarStyle: UIStatusBarStyle {
    return darkModeOn ? .lightContent : .default
}

but is shows only the light status bar但只显示灯状态栏

In Info.plist set "View controller-based status bar appearance" to YES.在 Info.plist 中,将“基于控制器的状态栏外观”设置为 YES。 If it's set to NO then it's gonna apply the default value to all view controllers.如果它设置为 NO ,那么它会将默认值应用于所有视图控制器。

Once it's set to yes use this to override the appearance in each view controller:一旦它被设置为 yes 使用它来覆盖每个视图控制器中的外观:

override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
    //or return .default
}

Try this, it works for me:试试这个,它对我有用:

  1. In Info.plist, set UIViewControllerBasedStatusBarAppearance to YES在 Info.plist 中,将UIViewControllerBasedStatusBarAppearance设置为YES
  2. Override preferredStatusBarStyle :覆盖preferredStatusBarStyle

    override var preferredStatusBarStyle: UIStatusBarStyle { return UserDefaults.standard.bool(forKey: "isDarkMode") ? .lightContent : .default }

BUT, if this view controller is embed in a navigation controller, the override will be ignored, so you must use this code instead:但是,如果此视图控制器嵌入到导航控制器中,则覆盖将被忽略,因此您必须改用以下代码:

self.navigationController?.navigationBar.barStyle = UserDefaults.standard.bool(forKey: "isDarkMode") ? .black : .default

Hope this helps希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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