how to change statusbar color in one view controller using swift?

Xcode 8.1, Swift 3 Solution with @IBDesignable

This solution is a little bit different:

  • Subclass of UIViewController to centralize logic
  • No code for viewDidLoad or viewDidDisappear
  • Uses @IBDesignable so you can set your status bar color in the Attributes Inspector on the Storyboard

Step 1 - Setup Info.plist File

Info.plist

Step 2 - Subclass UIViewController

import UIKit

@IBDesignable
class DesignableViewController: UIViewController {

    @IBInspectable var LightStatusBar: Bool = false

    override var preferredStatusBarStyle: UIStatusBarStyle {
        get {
            if LightStatusBar {
                return UIStatusBarStyle.lightContent
            } else {
                return UIStatusBarStyle.default
            }
        }
    }
}

Step 3 - Inherit from DesignableViewController

Change the code for your ViewController(s) from:

class ViewController: UIViewController {

To:

class ViewController: DesignableViewController {

Step 4 - Set your preference on the Storyboard

Select the ViewControllers on the Storyboard and go to the Attributes Inspector: Attributes Inspector

Step 5 - Run project and test

In my project I setup a Tab Bar Controller with 2 View Controllers and switch back and forth between the two. Seems to work OK for me. Light Status Bar Dark Status Bar


Set View controller-based status bar appearance in your project.plist to NO

Use viewWillAppear and will viewWillDisappear to set and reset the statusBarStyle, while keeping a property with the previous statusBarStyle like this

let initialStatusBarStyle : UIStatusBarStyle

func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    initialStatusBarStyle = UIApplication.sharedApplication().statusBarStyle
    UIApplication.sharedApplication().setStatusBarStyle(.LightContent, animated: animated)
}

func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)
    UIApplication.sharedApplication().setStatusBarStyle(initialStatusBarStyle, animated: animated)
}

Swift 3

Set View controller-based status bar appearance in your project.plist to NO

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    UIApplication.shared.setStatusBarStyle(.default, animated: animated)
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    UIApplication.shared.setStatusBarStyle(.lightContent, animated: animated)
}

Solved:
Swift 3.1

Just using this code in View Controller:

override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
}

Tags:

Ios

Xcode

Swift