You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS Swift 5 单场景如何禁止自动旋转 仅支持点击按钮手动切换设备方向

iOS Swift 5 单场景自定义设备方向适配实现方案

前置配置

首先在Xcode项目的「General」-「Deployment Info」-「Device Orientation」中,勾选所有你需要支持的方向(至少要勾选本次用到的竖屏、左横屏选项),全局方向配置是页面单独调整的前提。

目标ViewController基础配置

重写两个系统内置属性,实现物理旋转时界面不跟随变化的需求:

// 禁用自动跟随物理设备旋转
override var shouldAutorotate: Bool {
    return false
}

// 声明当前页面支持的所有可选方向
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return [.portrait, .landscapeLeft]
}

按钮点击触发左旋转逻辑

在按钮点击事件中添加以下兼容代码,覆盖全iOS系统版本:

@IBAction func rotateLeftAction(_ sender: UIButton) {
    if #available(iOS 16.0, *) {
        // iOS 16+ 官方标准API实现
        guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene else { return }
        windowScene.requestGeometryUpdate(.iOS(interfaceOrientations: .landscapeLeft)) { error in
            print("方向调整失败:\(error.localizedDescription)")
        }
        self.setNeedsUpdateOfSupportedInterfaceOrientations()
    } else {
        // iOS 15 及更低版本兼容实现
        UIDevice.current.setValue(UIInterfaceOrientation.landscapeLeft.rawValue, forKey: "orientation")
        UINavigationController.attemptRotationToDeviceOrientation()
    }
}

注意事项

  • 如果当前ViewController嵌套在UINavigationController或者UITabBarController等容器控制器中,需要给容器控制器添加扩展,重写方向相关属性,返回当前顶层显示页面的配置,否则方向控制不会生效,以下为UINavigationController的扩展示例:
extension UINavigationController {
    open override var shouldAutorotate: Bool {
        return topViewController?.shouldAutorotate ?? false
    }
    
    open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return topViewController?.supportedInterfaceOrientations ?? .portrait
    }
}
  • 退出当前页面时如果需要恢复全局默认方向,可在viewWillDisappear生命周期方法中调用相同的旋转逻辑,切回指定方向即可。

内容的提问来源于stack exchange,提问作者Levan Karanadze

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 21:24:03