SwiftUI 屏幕旋转监听实现

2020-04-09  本文已影响0人  fordG

swiftUI我好像没有找到屏幕旋转的方法,于是利用EnvironmentObject来实现了一个旋转

*model

class GlobalModel: ObservableObject{
    
    @Published var orientationType: UIDeviceOrientation = .portrait
    
    init() {
        // 检测设备方向
        NotificationCenter.default.addObserver(self, selector: #selector(receivedRotation), name: UIDevice.orientationDidChangeNotification, object: nil)
    }
    
    func resetPushed(){
        self.LoginPassworPushed = false
        self.LoginMsgPushed = false
    }
    
    //通知监听触发的方法
    @objc func receivedRotation(){
        // 屏幕方向
        self.orientationType = UIDevice.current.orientation
//        switch UIDevice.current.orientation {
//        case UIDeviceOrientation.unknown:
//            print("方向未知")
//        case .portrait: // Device oriented vertically, home button on the bottom
//            print("屏幕直立")
//        case .portraitUpsideDown: // Device oriented vertically, home button on the top
//            print("屏幕倒立")
//        case .landscapeLeft: // Device oriented horizontally, home button on the right
//            print("屏幕左在上方")
//        case .landscapeRight: // Device oriented horizontally, home button on the left
//            print("屏幕右在上方")
//        case .faceUp: // Device oriented flat, face up
//            print("屏幕朝上")
//        case .faceDown: // Device oriented flat, face down
//            print("屏幕朝下")
//        }
    }
}

*然后利用 orientationType属性的改变来获取屏幕转动之后的操作,也可以自定义一个class,通过闭包来回掉监听的结果

上一篇下一篇

猜你喜欢

热点阅读