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