How we can find out iPad orientation in SwiftUI, automatically getting notification or get update with a function?

406 views Asked by At

I want to get notified when user changes iPad orientation. In UIKit that was easy but I do not know how we can get that information with SwiftUI?

1

There are 1 answers

6
pawello2222 On BEST ANSWER

You can try:

UIApplication.shared.windows.first?.windowScene?.interfaceOrientation.isLandscape ?? false

or:

UIDevice.current.orientation.isLandscape

If you want to detect notifications you can listen to UIDevice.orientationDidChangeNotification:

UIDevice.current.beginGeneratingDeviceOrientationNotifications()
...
.onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)) { ... }

Here is a demo:

@main
struct TestApp: App {
    init() {
        UIDevice.current.beginGeneratingDeviceOrientationNotifications()
    }

    var body: some Scene {
        WindowGroup {
            Text("Test")
                .onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)) { _ in
                    print(UIApplication.shared.windows.first?.windowScene?.interfaceOrientation.isLandscape ?? false)
                }
        }
    }
}