Jerny
Jerny

Reputation: 151

How to set statusBar color on iPhoneX?

I use the navigationController, and i hide the navigationBar, how to set statusBar color on iPhoneX? I do not want to set self.view.backgroundColor

iPhoneX notch color

enter image description here

Upvotes: 9

Views: 8979

Answers (4)

Ahmadreza
Ahmadreza

Reputation: 7212

Swift 4

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

Upvotes: 2

Jerny
Jerny

Reputation: 151

UIView *statusBar = (UIView *)[[UIApplication sharedApplication] valueForKey:@"statusBar"];
statusBar.backgroundColor = [UIColor greenColor];

Upvotes: 4

arlomedia
arlomedia

Reputation: 9061

In Interface Builder, I simply added a view at 0x0, 44px high and the same width as the top-level view, then set this view to the desired background color. This changed the background color of the status bar without affecting the view background color.

In my case, I needed something like this because the top half of my screen is one color and the bottom half is the other. I didn't see another way to make the status bar match the top color and the home button area match the bottom color.

This could easily be done programmatically if the extra view gets in the way on devices other than the iPhone X. In my case it doesn't cause problems on other devices.

Upvotes: 0

Krunal
Krunal

Reputation: 79676

Here is a hacky trick to change/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

Upvotes: 3

Related Questions