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

Xcode中如何仅允许单个UIViewController支持倒置旋转?

第一步:配置App全局默认竖屏规则
  • 打开Xcode项目的General设置页,找到Deployment Info下的Device Orientation选项,仅勾选Portrait(竖屏),完成全局默认方向配置。
  • 也可以通过AppDelegate的代理方法全局控制,代码如下:
// Objective-C版本
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    return UIInterfaceOrientationMaskPortrait;
}
// Swift版本
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    return .portrait
}
第二步:重写目标ViewController的方向控制属性

注意:如果目标ViewController嵌套在UINavigationController/UITabBarController等容器中,需要先给容器类加扩展,优先读取当前顶层显示ViewController的方向配置

目标ViewController的配置代码:

// Objective-C版本
// 开启自动旋转
- (BOOL)shouldAutorotate {
    return YES;
}
// 支持的方向:竖屏 + 倒置竖屏
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown;
}
// 进入页面默认方向
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationPortrait;
}
// Swift版本
override var shouldAutorotate: Bool {
    return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return [.portrait, .portraitUpsideDown]
}
override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
    return .portrait
}
第三步:容器类适配(使用导航/标签栏控制器时需要)

以UINavigationController为例,给容器类加扩展重写方向属性:

// Swift导航控制器适配示例
extension UINavigationController {
    open override var shouldAutorotate: Bool {
        return topViewController?.shouldAutorotate ?? false
    }
    open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return topViewController?.supportedInterfaceOrientations ?? .portrait
    }
    open override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return topViewController?.preferredInterfaceOrientationForPresentation ?? .portrait
    }
}

如果使用UITabBarController,同理扩展后取当前选中的ViewController的方向配置即可。

适配注意事项
  • iPhone X及之后的全面屏机型系统默认不支持倒置竖屏,如需适配需额外做兼容性处理
  • iOS 16及以上版本废弃了部分旧方向控制API,切换方向时需要额外调用方法触发更新:
if #available(iOS 16.0, *) {
    self.setNeedsUpdateOfSupportedInterfaceOrientations()
}
  • 从支持旋转的页面跳转回普通页面时,系统会自动切回默认竖屏,无需手动处理

内容的提问来源于stack exchange,提问作者Stanislav Putilov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 00:36:04