我们如何在 SwiftUI 中找到 iPad 方向,自动获取通知或使用函数获取更新?

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

我想在用户更改 iPad 方向时收到通知。在 UIKit 中这很容易,但我不知道我们如何使用 SwiftUI 获取该信息?

你可以试试:

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

或:

UIDevice.current.orientation.isLandscape

如果你想检测通知你可以听 UIDevice.orientationDidChangeNotification:

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

这是一个演示:

@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)
                }
        }
    }
}