小编NNN*_*NNN的帖子

iOS16 中 swiftUI 中的屏幕方向旋转

我正在开发一个使用视图控制器的应用程序,并且正在慢慢迁移到使用使用 SwiftUI 构建的视图。

我正在开发新的 swiftUI 视图,因此我将 UIHostingController 设置为 SceneDelegate 中的 rootViewController

总的来说,我的整个应用程序仅限于此处的纵向

在此输入图像描述

我希望允许在左侧纵向和横向显示一些个人视图

这是我到目前为止所使用的 swiftUI,它在 iOS 15 中完美运行

在 AppDelegate 我有

static var orientationLock = UIInterfaceOrientationMask.portrait
Run Code Online (Sandbox Code Playgroud)

然后在方法中

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask 
Run Code Online (Sandbox Code Playgroud)

这设置为返回

return AppDelegate.orientationLock
Run Code Online (Sandbox Code Playgroud)

然后在特定的 swiftUI 文件中我想要允许旋转,我只需通过将此修改器添加到主视图来处理屏幕旋转

.onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)) { _ in
            
            if orientation.isLandscape {
                AppDelegate.orientationLock = UIInterfaceOrientationMask.landscapeLeft
                UIDevice.current.setValue(UIInterfaceOrientation.landscapeLeft.rawValue, forKey: "orientation")
                UINavigationController.attemptRotationToDeviceOrientation()
            } else {
                AppDelegate.orientationLock = UIInterfaceOrientationMask.portrait
                UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
                UINavigationController.attemptRotationToDeviceOrientation()
            }
            
        }
        .onDisappear {
            DispatchQueue.main.async {
                AppDelegate.orientationLock = UIInterfaceOrientationMask.portrait
                UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
                UINavigationController.attemptRotationToDeviceOrientation() …
Run Code Online (Sandbox Code Playgroud)

screen-orientation screen-rotation ios swiftui ios16

6
推荐指数
0
解决办法
1477
查看次数