Change status bar color dynamically in Swift 4

后端 未结 3 1101
天命终不由人
天命终不由人 2021-01-31 22:11

I would like to change the status bar color between .lightContent and .default dynamically (since my background can change in the same ViewController).

相关标签:
3条回答
  • 2021-01-31 22:30

    Create a property with type UIStatusBarStyle and return the value in preferredStatusBarStyle

    And you can change its value whenever you need and call setNeedsStatusBarAppearanceUpdate()

    class ViewController: UIViewController {
    
        override var preferredStatusBarStyle: UIStatusBarStyle {
            return self.style
        }
        var style:UIStatusBarStyle = .default
    
        override func viewDidLoad() {
            super.viewDidLoad()
        }
    
        @IBAction func changeStyle(_ sender: UIButton) {
            if self.style == .lightContent {
                self.style = .default
            } else {
                self.style = .lightContent
            }
            setNeedsStatusBarAppearanceUpdate()
        }
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle { return self.style }
    

    wont be called if you have embedded your view controller in a navigation controller You should change bar style of your navigation controller

    self.navigationController?.navigationBar.barStyle = //newStyle
    

    0 讨论(0)
  • 2021-01-31 22:35

    Override preferredStatusBarStyle and call setNeedsStatusBarAppearanceUpdate() when it needs an update. In my example I used a simple dark mode controlled by a boolean property useDarkMode. As soon as it gets changed the UI is updated (including the status bar):

    var useDarkMode = false {
        didSet {
            if useDarkMode != oldValue {
                updateUI()
            }
        }
    }
    
    private func updateUI() {
        UIView.animate(withDuration: 0.25) {
            if self.useDarkMode {
                self.view.backgroundColor = .darkGray
                self.view.tintColor = .white
            } else {
                self.view.backgroundColor = .white
                self.view.tintColor = nil
            }
    
            self.setNeedsStatusBarAppearanceUpdate()
        }
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return useDarkMode ? .lightContent : .default
    }
    
    0 讨论(0)
  • 2021-01-31 22:46

    I hope below code will use for your need (for Swift4):

    override func viewDidLoad() {
        super.viewDidLoad()
    
        let statusBar = UIApplication.shared.value(forKey: "statusBar") as? UIView
        if statusBar?.responds(to: #selector(setter: UIView.backgroundColor)) ?? false {
            statusBar?.backgroundColor = .green
        }
    }
    

    Alternatively, you could try this:

       if let StatusbarView = UIApplication.shared.value(forKey: "statusBar") as? UIView {
                    StatusbarView.backgroundColor = .green
       }
    
    0 讨论(0)
提交回复
热议问题