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

iOS 16中阻止UIViewController旋转失效,原shouldAutorotate方法无效求助

iOS 16 下阻止ViewController旋转的解决方案

iOS 16 对UIKit的屏幕旋转逻辑做了调整,原有的shouldAutorotate属性不再被系统优先调用,所以你之前的方法失效了。可以通过以下步骤解决:

  • 重写ViewController的supportedInterfaceOrientations属性,根据录制状态返回对应的支持方向:
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        if screenRecorderIsActive {
            // 固定为当前设备方向,或者指定某个特定方向(比如.portrait)
            return UIApplication.shared.windows.first?.windowScene?.interfaceOrientation.mask ?? .portrait
        } else {
            return .all
        }
    }
    
  • 当screenRecorderIsActive状态变化时,主动通知系统更新支持的方向:
    // 假设你在某个方法里修改了screenRecorderIsActive的值
    screenRecorderIsActive = !screenRecorderIsActive
    setNeedsUpdateOfSupportedInterfaceOrientations()
    

注意事项

如果你的ViewController嵌套在导航控制器、标签栏控制器这类容器控制器中,需要确保容器控制器会传递子控制器的旋转设置。可以通过扩展容器控制器实现:

导航控制器扩展

extension UINavigationController {
    override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return topViewController?.supportedInterfaceOrientations ?? .all
    }
}

标签栏控制器扩展

extension UITabBarController {
    override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return selectedViewController?.supportedInterfaceOrientations ?? .all
    }
}

这样设置后,当屏幕录制激活时,控制器会锁定当前方向;录制结束后,恢复支持所有方向的旋转。

内容的提问来源于stack exchange,提问作者Dmitry Zheshinsky

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 07:45:19