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
相关产品推荐
相关产品推荐

