Changing the Status Bar Color for specific ViewControllers using Swift in iOS8

Anuj picture Anuj · Nov 16, 2014 · Viewed 228.1k times · Source
override func preferredStatusBarStyle() -> UIStatusBarStyle {
 return UIStatusBarStyle.LightContent;
}

Using the above code in any ViewController to set the statusBar color to White for a specific viewcontroller doesnt work in iOS8 for me. Any suggestions? Using the UIApplication.sharedApplication method, the color changes after required changes in the Info.plist for the whole app.

// Change the colour of status bar from black to white
UIApplication.sharedApplication().statusBarStyle = .LightContent

How can I just make changes to the status bar color for some required and specific ViewControllers?

Answer

Anuj picture Anuj · Feb 14, 2015

After reading all the suggestions, and trying out a few things, I could get this to work for specific viewcontrollers using the following steps :

First Step:

Open your info.plist and insert a new key named "View controller-based status bar appearance" to NO

Second Step (Just an explanation, no need to implement this):

Normally we put the following code in the application(_:didFinishLaunchingWithOptions:) method of the AppDelegate,

Swift 2

UIApplication.sharedApplication().statusBarStyle = .LightContent

Swift 3

UIApplication.shared.statusBarStyle = .lightContent

but that affects the statusBarStyle of all the ViewControllers.

So, how to get this working for specific ViewControllers - Final Step:

Open the viewcontroller file where you want to change the statusBarStyle and put the following code in viewWillAppear(),

Swift 2

UIApplication.sharedApplication().statusBarStyle = .LightContent

Swift 3

UIApplication.shared.statusBarStyle = .lightContent

Also, implement the viewWillDisappear() method for that specific viewController and put the following lines of code,

Swift 2

override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)
    UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.Default

}

Swift 3

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    UIApplication.shared.statusBarStyle = UIStatusBarStyle.default
}

This step will first change the statusBarStyle for the specific viewcontroller and then change it back to default when the specific viewcontroller disappears. Not implementing the viewWillDisappear() will change the statusBarStyle permanently to the new defined value of UIStatusBarStyle.LightContent