简体   繁体   中英

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. I set the default status bar as 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. If it's set to NO then it's gonna apply the default value to all view controllers.

Once it's set to yes use this to override the appearance in each view controller:

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

Try this, it works for me:

  1. In Info.plist, set UIViewControllerBasedStatusBarAppearance to YES
  2. Override 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

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