Status bar height in SwiftUI in iOS 13

1.4k Views Asked by At

How do you get the current scene's status bar height for use in a SwiftUI view?

It looks like the key is accessing the current scene. From a view controller, you can use view.window?.windowScene to get to the scene, but what about in a SwiftUI view?

1

There are 1 best solutions below

0
On

Store the window scene in an environment object when creating the view hierarchy. The environment object can be an existing object that you use for other app-wide data.

final class AppData: ObservableObject {
    let windowScene: UIWindow? // Will be nil in SwiftUI previewers

    init(windowScene: UIWindowScene? = nil) {
        self.windowScene = windowScene
    }
}

Set the window scene when you create the environment object. Add the object to the view at the base of your view hierarchy, such as the root view.

let rootView = RootView().environmentObject(AppData(windowScene: windowScene))

Finally, use the window scene to access the status bar height.

struct MyView: View {
    @EnvironmentObject private var appData: AppData
    ...
    var body: some View {
        SomeView().frame(height: self.appData.windowScene?.statusBarManager?.statusBarFrame.height ?? 0)
    }
}