自定义UIViewController界面Orientation获取异常,求正确获取方案
正确获取自定义ViewController界面方向的方案
你遇到的问题本质是:windowScene?.interfaceOrientation返回的是系统全局/物理层面的设备方向,但当你通过supportedInterfaceOrientations限制了当前控制器的旋转方向时,控制器实际显示的方向可能和全局方向不一致——而废弃的interfaceOrientation方法恰好是直接返回控制器自身的界面方向,所以结果正确。
下面是两种可靠的替代方案:
方案1:结合支持方向与全局方向计算
通过对比全局方向和当前控制器允许的旋转方向,筛选出实际生效的界面方向,同时 fallback 到界面尺寸判断(应对设备平放等特殊情况):
public var currentInterfaceOrientation: UIInterfaceOrientation { let globalOrientation = view.window?.windowScene?.interfaceOrientation ?? .unknown let supportedOrientations = self.supportedInterfaceOrientations // 如果全局方向在控制器支持范围内,直接返回 if supportedOrientations.contains(globalOrientation) { return globalOrientation } // 否则根据界面宽高判断当前实际方向 let isPortrait = view.bounds.width <= view.bounds.height // 可根据你支持的方向调整默认值,比如如果只支持竖屏就返回.portrait return isPortrait ? .portrait : .landscapeLeft }
方案2:维护本地方向变量(更精准)
自己维护一个记录当前方向的变量,在方向变化回调和控制器初始化时更新,完全匹配控制器实际显示的方向:
private var _currentOrientation: UIInterfaceOrientation = .portrait public var currentInterfaceOrientation: UIInterfaceOrientation { return _currentOrientation } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // 初始化方向 updateCurrentOrientation() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) // 方向变化时更新变量 coordinator.animate(alongsideTransition: { _ in self.updateCurrentOrientation() }) } private func updateCurrentOrientation() { if let globalOrientation = view.window?.windowScene?.interfaceOrientation, supportedInterfaceOrientations.contains(globalOrientation) { _currentOrientation = globalOrientation } else { let isPortrait = view.bounds.width <= view.bounds.height _currentOrientation = isPortrait ? .portrait : .landscapeLeft } }
注意点
- 不要直接依赖
UIDevice.current.orientation:它返回的是设备物理方向,和界面方向可能存在偏差(比如设备倒转但控制器不允许旋转),仅适合作为 fallback。 - 如果你的支持方向包含特定的横屏/竖屏子集,可在代码中针对性调整默认返回值,比如只支持
portraitUpsideDown的话,就把竖屏判断的返回值改成.portraitUpsideDown。
内容的提问来源于stack exchange,提问作者Deepak Sharma
相关产品推荐
相关产品推荐

