Ulugbek
Ulugbek

Reputation: 147

How to change the color of status bar to a custom color other than light and dark in iOS 14, Swift 5?

I want to change the color of status bar (battery percentage, time and wifi, etc) to a custom color (red, yellow, blue, etc) other than .lightContent and .darkContent that Apple offers. Is that even possible to do so? if yes please help me to solve this problem. I have seen the answers on google and stackoverflow, but they only change the backgroundColor mostly the deprecation of keyWindow. I am using Swift 5 and iOS 14.4.

Upvotes: 3

Views: 1845

Answers (1)

Piyush Sharma
Piyush Sharma

Reputation: 109

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
}

That’s it :) Do not forget to use it on viewDidLoad function. If you are using TabBarController this code segment should be on viewWillAppear function. This is important!

Upvotes: 1

Related Questions