Swift 5 如何在iPad上实现手动修改设备屏幕朝向的功能
iPad端手动修改屏幕朝向实现方案
iPad默认支持分屏多任务特性,系统会禁止应用主动强制修改屏幕朝向,需完成配置和代码适配后生效:
1. 项目配置调整
- 打开Xcode项目的
General设置页,找到「Deployment Info」板块 - 勾选Requires full screen选项,关闭多任务适配限制,这是iPad端强制转屏生效的必要前提
- 检查「Supported interface orientations (iPad)」配置,确保所有需要切换的屏幕朝向都已勾选,对应Info.plist中的
UISupportedInterfaceOrientations~ipad数组要包含目标朝向的枚举值
2. 代码适配调整
首先需要在需要转屏的ViewController中重写supportedInterfaceOrientations属性,动态返回当前需要支持的朝向,如果页面嵌套在UINavigationController/UITabBarController等容器中,需要同步重写容器控制器的对应属性,优先返回最上层显示页面的配置:
// 新增:变量控制当前支持的朝向 var currentSupportedOrientations: UIInterfaceOrientationMask = .all override public var supportedInterfaceOrientations: UIInterfaceOrientationMask { return currentSupportedOrientations } override public var shouldAutorotate: Bool { return true } func rotate() { let targetOrientation = nextDeviceOrientation() // 先更新当前支持的朝向配置 switch targetOrientation { case .portrait: currentSupportedOrientations = .portrait case .landscapeLeft: currentSupportedOrientations = .landscapeLeft case .landscapeRight: currentSupportedOrientations = .landscapeRight case .portraitUpsideDown: currentSupportedOrientations = .portraitUpsideDown default: break } UIDevice.current.setValue(targetOrientation.rawValue, forKey: "orientation") UINavigationController.attemptRotationToDeviceOrientation() // 转屏完成后重置支持的朝向,方便后续切换 DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { self.currentSupportedOrientations = .all } }
3. iOS16+ 官方公开API实现(无审核风险)
如果应用最低支持iOS16及以上,可使用官方公开API实现,避免KVC访问私有属性可能带来的App Store审核问题:
func rotateiOS16() { if #available(iOS 16.0, *) { let targetOrientation: UIInterfaceOrientationMask = .landscapeLeft // 替换为nextDeviceOrientation返回的目标朝向对应枚举 self.setNeedsUpdateOfSupportedInterfaceOrientations() guard let windowScene = self.view.window?.windowScene else { return } windowScene.requestGeometryUpdate(.iOS(interfaceOrientations: targetOrientation)) { error in // 处理转屏失败逻辑 print("转屏失败:\(error)") } } }
内容的提问来源于stack exchange,提问作者Levan Karanadze
相关产品推荐
相关产品推荐

