如何在单个ViewController中锁定左右横屏方向?代码无效问题排查
解决单个ViewController锁定横屏左右方向不生效的问题
错误点1:
shouldAutorotate返回值错误
你将shouldAutorotate设为false,会直接禁止当前VC的自动旋转功能,即便设置了支持的方向,设备旋转时也不会响应。要让VC跟随设备旋转并限制方向,这个属性应返回true:override var shouldAutorotate: Bool { return true } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .landscape // 包含横屏左、横屏右两个方向 }检查全局方向配置
确保项目Info.plist中,UISupportedInterfaceOrientations(iOS)和UISupportedInterfaceOrientations~ipad(iPad)已添加LandscapeLeft和LandscapeRight方向。若全局未开启这些方向,单个VC的设置无法生效。处理容器控制器的影响
如果你的ViewController被UINavigationController、UITabBarController这类容器控制器包裹,系统会优先询问容器控制器的旋转设置,而非当前显示的子VC。需给容器控制器添加扩展,转发旋转决策给顶层子VC:针对
UINavigationController:extension UINavigationController { override open var shouldAutorotate: Bool { return topViewController?.shouldAutorotate ?? super.shouldAutorotate } override open var supportedInterfaceOrientations: UIInterfaceOrientationMask { return topViewController?.supportedInterfaceOrientations ?? super.supportedInterfaceOrientations } }针对
UITabBarController:extension UITabBarController { override open var shouldAutorotate: Bool { return selectedViewController?.shouldAutorotate ?? super.shouldAutorotate } override open var supportedInterfaceOrientations: UIInterfaceOrientationMask { return selectedViewController?.supportedInterfaceOrientations ?? super.supportedInterfaceOrientations } }
内容的提问来源于stack exchange,提问作者User
相关产品推荐
相关产品推荐

