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

强制.landscapeRight横屏时UIImage及导航栏未旋转的问题

解决导航控制器下横屏不生效的问题

这个坑我之前踩过!你猜的没错,默认UINavigationController不传递子控制器的旋转设置就是核心问题。系统自带的导航控制器会用自己的旋转逻辑,完全忽略你在子VC里设置的.landscapeRight,导致UIImage和导航栏没跟着旋转,手动转设备相当于触发了系统的旋转检测,才恢复正常。

下面给你具体的解决步骤:

1. 自定义NavigationController类

创建一个继承自UINavigationController的自定义类,把旋转逻辑委托给当前显示的子控制器:

import UIKit

class CustomNavigationController: UINavigationController {
    override var shouldAutorotate: Bool {
        return topViewController?.shouldAutorotate ?? super.shouldAutorotate
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return topViewController?.supportedInterfaceOrientations ?? super.supportedInterfaceOrientations
    }
    
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return topViewController?.preferredInterfaceOrientationForPresentation ?? super.preferredInterfaceOrientationForPresentation
    }
}

之后在Storyboard里选中你的导航控制器,在Identity Inspector里把Class改成CustomNavigationController。

2. 完善子ViewController的旋转配置

确保你的目标VC里的旋转设置正确,并且主动触发一次旋转刷新:

class TargetLandscapeVC: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        // 主动触发旋转更新,避免启动时不生效
        if let window = UIApplication.shared.windows.first {
            window.rootViewController?.setNeedsUpdateOfSupportedInterfaceOrientations()
            UIViewController.attemptRotationToDeviceOrientation()
        }
    }
    
    override var shouldAutorotate: Bool {
        return true
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .landscapeRight
    }
    
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return .landscapeRight
    }
}

3. 检查Info.plist的支持方向

别忘记在Info.plist里添加Landscape Right到Supported interface orientations数组中,否则系统会限制旋转方向,导致设置不生效。

这样修改后,导航控制器会完全遵循子VC的旋转要求,启动时就能直接切换到.landscapeRight,UIImage和导航栏也会正常旋转了!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:03:20