I would like to change the status bar color between .lightContent
and .default
dynamically (since my background can change in the same ViewController).
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
}