1

I'm trying to get the updated status bar frame height using didChangeStatusBarFrame, but…

The new/updated frame isn't up-to-date and sometimes returns the old and sometimes the new (correct) height.

func application(_ application: UIApplication, didChangeStatusBarFrame oldStatusBarFrame: CGRect) {
    print(UIApplication.shared.statusBarFrame.height) // Sometimes wrong
}

My current workaround is to use DispatchQueue.main.async:

func application(_ application: UIApplication, didChangeStatusBarFrame oldStatusBarFrame: CGRect) {
    DispatchQueue.main.async {
        print(UIApplication.shared.statusBarFrame.height) // So far correct in all my tests
    }
}

I guess it's because some layout is happening in the background and the statusBarFrame needs to update first.

What's the real reason and is there a better, not-so-hacky way to wait for the correct status bar frame height?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
tobi
  • 1,924
  • 2
  • 20
  • 25
  • My first thought is "why do you need the status bar frame height?". If you are looking to resize or move something you should probably be doing that with layout constraints rather than trying to watch the status bar's height. Can you provide more details about wha the overall effect you are trying to achieve might be? – Scott Thompson Jan 24 '19 at 19:26
  • I'm trying to create a view with the size and position of the status bar. See https://stackoverflow.com/questions/54350803/ios-status-bar-background-overlaps-uialertcontroller – tobi Jan 24 '19 at 19:32
  • The problem is similar to [this one](https://stackoverflow.com/questions/29242916/viewwilltransitiontosize-and-wrong-navigationbar-and-statusbarframe-heights), but there's no `coordinator` I can use to wait for the update. – tobi Jan 24 '19 at 19:37
  • Your code should probably respond to the application:didChangeStatusBarFrame: message by sending a "needsLayout" message to the parent of the view that contains the view you want to put behind the status bar. That needsLayout message will be called from the main thread during view layout and the status bar height should be set at that point. – Scott Thompson Jan 24 '19 at 19:41
  • Sounds reasonable, but it's not working. I've tried it with `view.setNeedsLayout(); view.layoutIfNeeded();` in the view containing the status bar view and before updating the height. – tobi Jan 24 '19 at 19:51

0 Answers0