0

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

4

1 回答 1

1

你可以试试:

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)
                }
        }
    }
}
于 2020-10-18T18:29:25.970 回答