我们如何在SwiftUI中找出iPad的方向,自动获得通知或使用功能进行更新?

问题描述

我想在用户更改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)
                }
        }
    }
}