简体   繁体   中英

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 .

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM