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

SwiftUI如何设置单个视图仅支持竖屏方向显示?

SwiftUI单个模态视图限制竖屏显示方案
  • 首先自定义继承自UIHostingController的子类,重写旋转和方向控制属性:
class OrientationLockedHostingController<Content: View>: UIHostingController<Content> {
    // 仅支持竖屏
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        .portrait
    }
    // 禁止自动跟随设备旋转
    override var shouldAutorotate: Bool {
        false
    }
}
  • 替换你原有的弹出代码,使用自定义的控制器即可:
let vc = OrientationLockedHostingController(rootView: MaModalView(title: "TEST"))
vc.modalPresentationStyle = .fullScreen
present(vc, animated: true)
  • 如果需要灵活适配不同页面的方向需求,可以对自定义控制器做扩展,支持动态配置方向:
class OrientationLockedHostingController<Content: View>: UIHostingController<Content> {
    // 对外暴露可配置的支持方向
    var supportedOrientations: UIInterfaceOrientationMask = .portrait
    // 对外暴露可配置的旋转开关
    var autoRotateEnabled: Bool = false
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        supportedOrientations
    }
    
    override var shouldAutorotate: Bool {
        autoRotateEnabled
    }
}

使用时按需赋值即可:

let vc = OrientationLockedHostingController(rootView: MaModalView(title: "TEST"))
// 可根据需求修改为其他方向组合,比如.landscapeLeft等
vc.supportedOrientations = .portrait
vc.autoRotateEnabled = false
vc.modalPresentationStyle = .fullScreen
present(vc, animated: true)

注意:需要提前在Xcode项目的「General - Deployment Info - Device Orientation」配置中,勾选你需要支持的方向(本场景需勾选Portrait竖屏),否则上述规则不会生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 23:27:00