最近在做腾讯超级播放器,在横屏状态需要显示键盘,所以需要自己实现controller的横屏设置(因为腾讯超级播放器是view单独横屏的)
废话不多说,说下解决方案(这里的场景是push的)
工程设置如图
设置设备横屏代码
extension UIDevice {
static func switchOrientation(_ orientation: UIInterfaceOrientation) {
let orientationTarget = NSNumber(value: orientation.rawValue)
UIDevice.current.setValue(orientationTarget, forKey: "orientation")
}
}
Appdelegate中需要初始化属性
var allowRotation: Bool = false
并实现
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
if allowRotation {
return [.landscapeRight, .landscapeLeft]
} else {
return .portrait
}
}
调用就很简单了
let app = AppDelegate.app()
if player.isFullScreen {
let originRotation = UIDevice.current.orientation
if UIDevice.current.orientation.isLandscape {
UIDevice.switchOrientation(UIInterfaceOrientation(rawValue: originRotation.rawValue) ?? .landscapeRight)
} else {
UIDevice.switchOrientation(.landscapeRight)
}
app?.allowRotation = true
app?.allowRotation = false // 旋转后必须重设,否则手动全屏后,选装手机,会造成退出全屏,但是controller还是横屏的bug
} else {
app?.allowRotation = false
UIDevice.switchOrientation(.portrait)
}
UIViewController.attemptRotationToDeviceOrientation()
期间遇到一些奇奇怪怪的问题,还是自己对这方面不熟悉吧
因为工程没有设置横屏,导致以上代码,连接Xcode Debug的时候,横屏一点问题没有,但是当断开Xcode连接,就没办法横屏了,
后来在对应controller下实现了如下方法, 断开连接就也没问题了
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return [.portrait, .landscapeRight, .landscapeLeft]
}
override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
return .portrait
}
注意:如果rootController有navigationcontroller 或者 tabbarController 需要对应设置
navigationController
override var shouldAutorotate: Bool {
return self.topViewController?.shouldAutorotate ?? false
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return self.topViewController?.supportedInterfaceOrientations ?? .portrait
}
override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
return self.topViewController?.preferredInterfaceOrientationForPresentation ?? .portrait
}
tabbarController
override var shouldAutorotate: Bool {
return self.selectedViewController?.shouldAutorotate ?? false
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return self.selectedViewController?.supportedInterfaceOrientations ?? .portrait
}
override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
return self.selectedViewController?.preferredInterfaceOrientationForPresentation ?? .portrait
}
到此为止,整个横屏设置算是完整了
一定要刷新当前控制器
UIViewController.attemptRotationToDeviceOrientation()
参考资料连接如下
在特定的View Controller允许屏幕旋转
iOS强制横屏总结
今天遇到present controller 默认进入横屏,设置 preferredInterfaceOrientationForPresentation 不生效的问题, 需要检查一下 需要present 的Vc的 modalPresentationStyle,我设置为overCurrentContext 横屏失败,设置为 overFullScreen就对了,有点蒙