I would like to change the status bar color between .lightContent
and .default
dynamically (since my background can change in the same ViewController).
I have tried to make a function for this that looks like this:
func changeStatusBar(useDefault: Bool) {
if useDefault {
var preferredStatusBarStyle: UIStatusBarStyle {
return .default
}
} else {
var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
setNeedsStatusBarAppearanceUpdate()
}
But no luck. Every guide i found online (or here on Stackoverflow) only shows how to change the statusBar once, and not on and off through a function.
I have also set View controller-based status bar appearance
to NO
in the info.plist
file.
The line i used to use is UIApplication.shared.statusBarStyle = .lightContent
- but since this is deprecated since iOS9, i can't use it anymore.
Anyone has some idea how I can change this dynamically?
Open your info. plist and set UIViewControllerBasedStatusBarAppearance to false . In the first function in AppDelegate. swift , which contains didFinishLaunchingWithOptions , set the color you want.
If you want to change the status bar color dynamically, you should call setNeedsStatusBarAppearanceUpdate() on your view controller, which will force preferredStatusBarStyle to be read again. Pro tip: you can put setNeedsStatusBarAppearanceUpdate() inside an animation block to have the change animate.
Step 1: After opening the android studio and creating a new project with an empty activity. Step 2: Navigate to res/values/colors. xml, and add a color that you want to change for the status bar. Step 3: In your MainActivity, add this code in your onCreate method.
To change the status bar to white: Open you Info. plist. Add View controller-based status bar appearance key ( UIViewControllerBasedStatusBarAppearance ) and set value to No ( false ).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With