Change Status Bar Background Color in Swift 3

IosSwiftSwift3StatusbarUistatusbar

Ios Problem Overview


In XCode 7.3.x ill changed the background Color for my StatusBar with:

func setStatusBarBackgroundColor(color: UIColor) {
guard  let statusBar = UIApplication.sharedApplication().valueForKey("statusBarWindow")?.valueForKey("statusBar") as? UIView else {
    return
}
statusBar.backgroundColor = color
}

But it seems that this is not working anymore with Swift 3.0.

Ill tried with:

func setStatusBarBackgroundColor(color: UIColor) {
guard  let statusBar = (UIApplication.shared.value(forKey: "statusBarWindow") as AnyObject).value(forKey: "statusBar") as? UIView else {
    return
}
statusBar.backgroundColor = color
}

But it gives me:

this class is not key value coding-compliant for the key statusBar.

Any Ideas how to change it with XCode8/Swift 3.0?

Ios Solutions


Solution 1 - Ios

extension UIApplication {
    var statusBarView: UIView? {
        if responds(to: Selector(("statusBar"))) {
            return value(forKey: "statusBar") as? UIView
        }
        return nil
    }
}

UIApplication.shared.statusBarView?.backgroundColor = .red

Update for iOS 13

> App called -statusBar or -statusBarWindow on UIApplication: this code > must be changed as there's no longer a status bar or status bar > window. Use the statusBarManager object on the window scene instead.

Refer to https://stackoverflow.com/questions/56651245/how-to-change-the-status-bar-background-color-and-text-color-on-ios-13

Solution 2 - Ios

"Change" status bar background color:

let statusBarView = UIView(frame: UIApplication.shared.statusBarFrame)
let statusBarColor = UIColor(red: 32/255, green: 149/255, blue: 215/255, alpha: 1.0)
statusBarView.backgroundColor = statusBarColor
view.addSubview(statusBarView)

Change status bar text color:

override var preferredStatusBarStyle: UIStatusBarStyle {
	return .lightContent
}

Update: please note that the status bar frame will change when the view is rotated. You could update the created subview frame by:

  • Using the autoresizing mask: statusBarView.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
  • Observing NSNotification.Name.UIApplicationWillChangeStatusBarOrientation
  • Or overriding viewWillLayoutSubviews()

Solution 3 - Ios

With using Swift 3 and 4 you can use the code snippet on below. It finds the view from UIApplication using valueForKeyPath as set it's background color.

guard let statusBarView = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView else {
        return
    }
statusBarView.backgroundColor = UIColor.red

Objective-C

UIView *statusBarView = [UIApplication.sharedApplication valueForKeyPath:@"statusBarWindow.statusBar"];
if (statusBarView != nil)
{
    statusBarView.backgroundColor = [UIColor redColor];
}

Solution 4 - Ios

For Xcode 9 and iOS 11: The style of the status bar we will try to achieve is a status bar with white content. Go to the ViewController.swift file and add the following lines of code.

override var preferredStatusBarStyle: UIStatusBarStyle {

     return .lightContent

}

Or from project settings option you can change status bar's style:

enter image description here

Next, go back to the Storyboard, Select the View Controller and in the Editor menu Select Embed in Navigation Controller. Select the Navigation Bar and in the Attribute Inspector set the Bar Tint color to red. The Storyboard will look like this. enter image description here

Build and Run the project, The content of the status bar is dark again, which is the default. The reason for this is, iOS asked for the style of the status bar of the navigation controller instead of the contained view controller.

enter image description here

To change the style of all navigation controller inside the app, change the following method in the AppDelegate.swift file.

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    
    UINavigationBar.appearance().barStyle = .blackOpaque
    return true
    }

Build and Run the Project again, this time the content of the status bar changed to white.

enter image description here

Solution 5 - Ios

I have a custom solution for changing status bar on iOS 13 and below. Here is how to do that:

if #available(iOS 13.0, *) {
   let app = UIApplication.shared
   let statusBarHeight: CGFloat = app.statusBarFrame.size.height

   let statusbarView = UIView()
   statusbarView.backgroundColor = UIColor.red
   view.addSubview(statusbarView)

   statusbarView.translatesAutoresizingMaskIntoConstraints = false
   statusbarView.heightAnchor
     .constraint(equalToConstant: statusBarHeight).isActive = true
   statusbarView.widthAnchor
     .constraint(equalTo: view.widthAnchor, multiplier: 1.0).isActive = true
   statusbarView.topAnchor
     .constraint(equalTo: view.topAnchor).isActive = true
   statusbarView.centerXAnchor
     .constraint(equalTo: view.centerXAnchor).isActive = true

} else {
      let statusBar = UIApplication.shared.value(forKeyPath: 
   "statusBarWindow.statusBar") as? UIView
      statusBar?.backgroundColor = UIColor.red
}

Gist

Also, check the article iOS 13 How to Change StatusBar Color?

One last thing, you can still change statusbar style with :

 override var preferredStatusBarStyle : UIStatusBarStyle {
    return UIStatusBarStyle.lightContent
    //return UIStatusBarStyle.default   // Make dark again
}

Solution 6 - Ios

For iOS 11 and Xcode 9 use the following steps.

  1. create an extention to UIApplication class:

    extension UIApplication { var statusBarView: UIView? { return value(forKey: "statusBar") as? UIView } }

  2. In your class or wherever you want to change the Status bar's background color:

    UIApplication.shared.statusBarView?.backgroundColor = .red

  3. For light content or dark content of status bar simply go to Info.plist and add the following value row with value NO.

> View controller-based status bar appearance

  1. Now just set the light content or whatever you need in the General Tab of your project's settings.

Solution 7 - Ios

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any] ?) -> Bool {
    // Override point for customization after application launch.

    UINavigationBar.appearance().barStyle = .blackOpaque
    return true
}

This works for me, as my navigation barTintColor was black and unable to see the status bar.

When set above code it didFinishLaunch status bar appears in white.

Solution 8 - Ios

I made this extension to change color of status bar. It's not dependent on the key. So it is much safer to use

public extension UIViewController {
    func setStatusBar(color: UIColor) {
        let tag = 12321
        if let taggedView = self.view.viewWithTag(tag){
            taggedView.removeFromSuperview()
        }
        let overView = UIView()
        overView.frame = UIApplication.shared.statusBarFrame
        overView.backgroundColor = color
        overView.tag = tag
        self.view.addSubview(overView)
    }
}

Here is usage anywhere in viewcontroller:

setStatusBar(color: .red)

Solution 9 - Ios

write this in first view controller:

UIApplication.shared.statusBarUIView?.backgroundColor = .white






extension UIApplication {
    var statusBarUIView: UIView? {
        if #available(iOS 13.0, *) {
            let tag = 38482458385
            if let statusBar = self.keyWindow?.viewWithTag(tag) {
                return statusBar
            } else {
                let statusBarView = UIView(frame: UIApplication.shared.statusBarFrame)
                statusBarView.tag = tag

                self.keyWindow?.addSubview(statusBarView)
                return statusBarView
            }
        } else {
            if responds(to: Selector(("statusBar"))) {
                return value(forKey: "statusBar") as? UIView
            }
        }
        return nil
    }
}

Solution 10 - Ios

Try this

Goto your app info.plist

  1. Set View controller-based status bar appearance to NO
  2. Set Status bar style to UIStatusBarStyleLightContent

Then Goto your app delegate and paste the following code where you set your Windows's RootViewController.

#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0"))
{
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width, 20)];
    view.backgroundColor=[UIColor blackColor];
    [self.window.rootViewController.view addSubview:view];
}

Solution 11 - Ios

Previous Code:-

func setStatusBarBackgroundColor(color: UIColor) {
        guard let statusBar = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView else { return }

        statusBar.backgroundColor = color
    }

My application got a crash show reason: 'App called -statusBar or -statusBarWindow on UIApplication: this code must be changed as there's no longer a status bar or status bar window. Use the statusBarManager object on the window scene instead.'

Updated Code-

  if #available(iOS 13.0, *) {
            let statusBar = UIView(frame: UIApplication.shared.keyWindow?.windowScene?.statusBarManager?.statusBarFrame ?? CGRect.zero)
             statusBar.backgroundColor = UIColor.init(red: 237.0/255.0, green: 85.0/255.0, blue: 61.0/255.0, alpha: 1.0)
             UIApplication.shared.keyWindow?.addSubview(statusBar)
        } else {
             UIApplication.shared.statusBarView?.backgroundColor = UIColor.init(red: 237.0/255.0, green: 85.0/255.0, blue: 61.0/255.0, alpha: 1.0)
        }

This code is working swift 5.2

enter image description here

Solution 12 - Ios

You can set background color for status bar during application launch or during viewDidLoad of your view controller.

extension UIApplication {

    var statusBarView: UIView? {
        return value(forKey: "statusBar") as? UIView
    }
    
}

// Set upon application launch, if you've application based status bar
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        UIApplication.shared.statusBarView?.backgroundColor = UIColor.red
        return true
    }
}


or 
// Set it from your view controller if you've view controller based statusbar
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        UIApplication.shared.statusBarView?.backgroundColor = UIColor.red
    }

}



Here is result:

enter image description here

Solution 13 - Ios

The possible solution is adding view that will be used as background of statusBar on your viewController:

let frame = screenController.view.convert(UIApplication.shared.statusBarFrame, to: screenController.view)
let backview = UIView(frame: frame)

backview.backgroundColor = backgroundColor
screenController.view.addSubview(backview)
screenController.view.bringSubviewToFront(backview)

Solution 14 - Ios

Add following code in your extension file to edit your status bar in swift 4 and Above:

extension UIApplication {
    var statusBarView: UIView? {
        if responds(to: Selector(("statusBar"))) {
            return value(forKey: "statusBar") as? UIView
        }
        return nil
    }
}

now, we can edit status bar by adding following line in our ViewController class:

UIApplication.shared.statusBarView?.backgroundColor = <Your Color name>

ex: UIApplication.shared.statusBarView?.backgroundColor = .red

Hope, this will be helpful. Thanks

Solution 15 - Ios

IOS 15, Xcode 13.2.1, Swift 5

I was able to get this to work without errors or warnings using the following:

func statusBarColor() {
    if #available(iOS 13.0, *) {
        
        let statusBar2 =  UIView()
        if UIApplication.shared.currentScene?.statusBarManager!.statusBarFrame != nil {
            statusBar2.frame = (UIApplication.shared.currentScene?.statusBarManager!.statusBarFrame)!
            statusBar2.backgroundColor = UIColor.init(named: "BackGroundColor")
            UIApplication.shared.windows.first?.addSubview(statusBar2)
        }
    } else {
        let statusBar2: UIView = UIApplication.shared.value(forKey: "statusBar") as! UIView
        statusBar2.backgroundColor = UIColor.init(named: "BackGroundColor")
    }
}

Use: Call the function in viewDidLoad for single scene applications or applications with only a single statusBar color change needed. For applications with multiple scenes calling for different statusBar colors I recommend calling the function in viewWillAppear.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionderdidaView Question on Stackoverflow
Solution 1 - IosCallamView Answer on Stackoverflow
Solution 2 - IosDaniel IllescasView Answer on Stackoverflow
Solution 3 - IosabdullahselekView Answer on Stackoverflow
Solution 4 - IosJamil Hasnine TamimView Answer on Stackoverflow
Solution 5 - IosFreakyCoderView Answer on Stackoverflow
Solution 6 - IosAsfand ShabbirView Answer on Stackoverflow
Solution 7 - IosioSanaView Answer on Stackoverflow
Solution 8 - IosRifat MonzurView Answer on Stackoverflow
Solution 9 - IosJainil PatelView Answer on Stackoverflow
Solution 10 - Iosvipinsaini0View Answer on Stackoverflow
Solution 11 - IosSushilView Answer on Stackoverflow
Solution 12 - IosKrunalView Answer on Stackoverflow
Solution 13 - IosDaniil ChuikoView Answer on Stackoverflow
Solution 14 - IosIshant IOSView Answer on Stackoverflow
Solution 15 - IosMichaelView Answer on Stackoverflow