4

Earlier on Xcode 10 and swift 5 I used to change the status bar color as follows:-

if let statusBar = UIApplication.shared.value(forKey: "statusBar") as? UIView {
   if statusBar.responds(to: #selector(setter: UIView.backgroundColor)) {
      statusBar.backgroundColor = #colorLiteral(red: 0, green: 0.7156304717, blue: 0.9302947521, alpha: 1)
   }
}

Now on Xcode 11 & Swift 5.1 I get the following error:-

Terminating app due to uncaught exception 'NSInternalInconsistencyException', 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.'

Any suggestions?

Wissa
  • 1,444
  • 20
  • 24
  • This question is a duplicate of https://stackoverflow.com/questions/56651245/how-to-change-the-status-bar-background-color-and-text-color-on-ios-13 – Hugo Alonso Jun 28 '19 at 15:33

1 Answers1

5

Try this:

extension UIApplication {


class var statusBarBackgroundColor: UIColor? {
    get {
        return statusBarUIView?.backgroundColor
    } set {
        statusBarUIView?.backgroundColor = newValue
    }
}

class var statusBarUIView: UIView? {
    if #available(iOS 13.0, *) {
        let tag = 987654321

        if let statusBar = UIApplication.shared.keyWindow?.viewWithTag(tag) {
            return statusBar
        }
        else {
            let statusBarView = UIView(frame: UIApplication.shared.statusBarFrame)
            statusBarView.tag = tag

            UIApplication.shared.keyWindow?.addSubview(statusBarView)
            return statusBarView
        }
    } else {
        if responds(to: Selector(("statusBar"))) {
            return value(forKey: "statusBar") as? UIView
        }
    }
    return nil
}}
Sattar
  • 393
  • 5
  • 18
  • 5
    I keep seeing this answer everywhere. Does it even work? Where does the tag value come from? – Motoko Sep 22 '19 at 05:29
  • 2
    yes it is working like a charm, the value of tag is something that you can decide ... we check that value to not adding the view on subview many times – Sattar Sep 23 '19 at 08:06
  • I use Xamarin Forms and this works for me, but `keyWindow` wasn't available until `viewWillAppear` is called. So I use it there instead of `FinishedLaunching` – Motoko Sep 24 '19 at 01:29
  • 2
    This is not using the new UIStatusBarManager nor the window.windowScene from iOS 13 (as recommended in the Xcode warning), but the trick does the work !!!, – eharo2 Oct 14 '19 at 19:47