美文网首页
Swift 监听设备方向

Swift 监听设备方向

作者: YourSummer | 来源:发表于2022-05-07 16:59 被阅读0次

思路: 通知监听

监听

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()
}

相关文章

网友评论

      本文标题:Swift 监听设备方向

      本文链接:https://www.haomeiwen.com/subject/klsxurtx.html