Swift 监听设备方向

2022-05-07  本文已影响0人  YourSummer

思路: 通知监听

监听

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

监听回调方法

@objc fileprivate func orientationDidChange() {
       // 首次运行项目会触发发四次该通知回调, 且第一次是unknown
        switch UIDevice.current.orientation {
        case .unknown:
            print("未知")
        case .portrait:
            print("竖屏")
        case .portraitUpsideDown:
            print("颠倒竖屏")
        case .landscapeLeft:
            print("设备向左旋转横屏")
        case .landscapeRight:
            print("设备向右旋转横屏")
        case .faceUp:
            print("屏幕朝上")
        case .faceDown:
            print("屏幕朝下")
        }
}

移除通知 & 结束生成设备旋转方向通知

deinit {
        // 移除通知
        NotificationCenter.default.removeObserver(self,
                                                  name: UIDevice.orientationDidChangeNotification,
                                                  object: nil)
        // 结束生成设备旋转方向通知
        UIDevice.current.endGeneratingDeviceOrientationNotifications()
}
上一篇 下一篇

猜你喜欢

热点阅读