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
}
这里固定上,就这样我们就完成了我们的横竖屏切换。 如有其他问题欢迎留言











