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

iOS锁定视图竖屏时如何检测设备方向变化事件

解决方案

viewWillTransition和traitCollectionDidChange是界面方向变化的回调,你锁了supportedInterfaceOrientations之后界面永远不会发生旋转,所以这两个方法自然不会触发。你要检测的是物理设备的朝向变化,需要使用设备层级的监听接口。


方案1:使用UIDevice方向通知(最简便)

这是最常用的实现方式,代码量小,满足绝大多数场景需求:

import UIKit

class YourViewController: UIViewController {
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // 开启设备方向通知生成
        UIDevice.current.beginGeneratingDeviceOrientationNotifications()
        // 注册方向变化监听
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(onDeviceOrientationChanged),
            name: UIDevice.orientationDidChangeNotification,
            object: nil
        )
    }

    @objc private func onDeviceOrientationChanged() {
        let orientation = UIDevice.current.orientation
        // 过滤平放、未知等非界面朝向(可选,可根据业务需求调整)
        guard orientation.isValidInterfaceOrientation else { return }
        
        switch orientation {
        case .portrait:
            print("设备当前为竖屏")
        case .portraitUpsideDown:
            print("设备当前为倒竖屏")
        case .landscapeLeft:
            print("设备当前为左横屏")
        case .landscapeRight:
            print("设备当前为右横屏")
        default:
            break
        }
    }

    deinit {
        // 移除监听、关闭通知生成,避免内存泄漏
        NotificationCenter.default.removeObserver(self)
        UIDevice.current.endGeneratingDeviceOrientationNotifications()
    }
}

注意事项:

  • 监听获取到的是物理设备的实际朝向,和当前界面方向无关,完全符合锁竖屏同时感知设备旋转的需求
  • UIDeviceOrientation包含faceUp/faceDown/unknown三类非界面朝向,可根据业务需求选择是否过滤

方案2:使用CoreMotion加速度计(可选,适用于特殊场景)

如果你的使用场景需要在设备平放时也能准确判断朝向,或者需要更高的检测精度,可以使用CoreMotion框架读取加速度计数据计算方向,实现逻辑稍复杂,常规场景不需要使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 17:15:03