old greg
old greg

Reputation: 897

How do I get a reference to the status bar in iOS 13+?

I am trying to blur the status bar like in Apple Maps. There are some solutions I've found on the internet but they're all a couple of years old at least and refer to deprecated properties, so I'e been trying to come up with a solution that works for iOS 13+ without any warnings.

Here's what I've tried:

func blurStatusBar() {
    let window = UIApplication.shared.windows.first(where: { $0.isKeyWindow })
    if let statusBarFrame = window?.windowScene?.statusBarManager?.statusBarFrame {
        let blurEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .regular))
        blurEffectView.frame = statusBarFrame
        view.addSubview(blurEffectView)
    }
}

However, this doesn't work. Using the debugger, I can see that window is nil, so it appears there are no windows that are set as the key window.

If I use let statusBarFrame = UIApplication.shared.statusBarFrame, it works, however I get a warning: ViewController.swift:66:51: 'statusBarFrame' was deprecated in iOS 13.0: Use the statusBarManager property of the window scene instead.

I am calling the above function in viewDidLoad from my initial view controller. Is this something I should be doing in my scene delegate instead of view controller?

Upvotes: 1

Views: 394

Answers (1)

matt
matt

Reputation: 534893

As in comedy, timing is everything. viewDidLoad is too soon. Your view controller has a view, but that view is not yet necessarily in a window and there is not yet necessarily a key window. Wait until something like viewDidLayoutSubviews when the initial interface hierarchy has been assembled (and add a check to make sure you don’t run the same code twice).

Upvotes: 3

Related Questions