位置:首页 > Swift > Swift开发中部分页面横屏失效问题解决方法

Swift开发中部分页面横屏失效问题解决方法

时间:2026-08-20  |  作者:318050  |  阅读:0
问题

我的项目是使用swift开发的,并且项目不支持横屏,但是某些页面必须要横屏,在iOS16以下我使用

UIDevice.current.setValue(isLandscape  UIInterfaceOrientation.landscapeRight.rawValue : UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")

进行横屏没问题.但是在iOS16及以上就会报一个bug

BUG IN CLIENT OF UIKIT: Setting UIDevice.orientation is not supported. Please use UIWindowScene.requestGeometryUpdate(_:)

意思就是在iOS16以上不支持这种横屏了,建议我们使用

UIWindowScene.requestGeometryUpdate(_:)

这个方法。但我在尝试将其用于横屏设置时,遭遇了报错,错误信息为:所有已请求的方向均不受视图控制器支持。已请求:landscapeRight;受支持:portrait

解决办法

下面是我的解决办法: 下面是解决的代码 先重写一下

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {

        return isLandscape  .landscape : .portrait

    }

    func switchScreenOrientation(isLandscape: Bool) {

            if #a vailable(iOS 16.0, *) {

                guard let scene = UIApplication.shared.connectedScenes.first as UIWindowScene else { return }

                let geometryPreferences = UIWindowScene.GeometryPreferences.iOS(interfaceOrientations: isLandscape  .landscapeRight : .portrait)

                setNeedsUpdateOfSupportedInterfaceOrientations()

                scene.requestGeometryUpdate(geometryPreferences) { error in

                    if !error.localizedDescription.isEmpty {

                        print("Error updating geometry: (error.localizedDescription)")

                    }

                }

            } else {

                if let appDelegate = UIApplication.shared.delegate as AppDelegate {

                    appDelegate.orientationLock = isLandscape  .landscape : .portrait

                    UIDevice.current.setValue(isLandscape  UIInterfaceOrientation.landscapeRight.rawValue : UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")

                    HomeLiveContentViewController.attemptRotationToDeviceOrientation() // 强制旋转

                }
            }
        }

这里是主要的代码但是我们还需要去info.plist中设置我们需要横屏的方向

这里需要进行一些设置。通过这里的设置,我们的项目就不再只是竖屏显示,而是会根据情况进行变化。此时,我们还需要在AppDelegate中添加一个

var orientationLock: UIInterfaceOrientationMask = .portrait
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {

        return orientationLock

    }

这里固定上,就这样我们就完成了我们的横竖屏切换。 如有其他问题欢迎留言

《夸克》非常好用的免费AI浏览器

下载APP查看

来源:整理自互联网
免责声明:文中图文均来自网络,如有侵权请联系删除,心愿游戏发布此文仅为传递信息,不代表心愿游戏认同其观点或证实其描述。

相关文章

更多

精选合集

更多

大家都在玩

热门话题

大家都在看

更多