首页 > 解决方案 > 在不旋转视图的情况下检测 iOS 设备方向变化

问题描述

我有一个 UIViewController,我想检测该 ViewController 上的设备方向变化。但我不想旋转视图。我的应用程序支持所有方向,但这个 ViewController 应该一直保持纵向模式。

我只能设置supportedInterfaceOrientations为纵向以获得所需的功能。但我仍然想知道这个 ViewController 中的方向变化。通常我可以使用viewWillTransition方法或traitCollectionDidChange方法来获取事件。但是当我设置supportedInterfaceOrientations为肖像时,这些方法都没有被调用。

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }

    // this method never get called
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
    }

当我仅设置为纵向时,有没有办法检测设备方向的变化?supportedInterfaceOrientations

标签: iosswift

解决方案


我认为您可以订阅通知

final class ViewController {
    override func viewDidLoad() {
        super.viewDidLoad() 
        NotificationCenter.default.addObserver(self, #selector(handleOrientationChange, name: UIDevice.orientationDidChangeNotification, object: nil))
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    @objc
    private func handleOrientationChange() {
        // Yay, orientation changed!
    }
}

推荐阅读