美文网首页
iOS使用陀螺仪判断屏幕方向

iOS使用陀螺仪判断屏幕方向

作者: 咸鱼有只喵 | 来源:发表于2018-08-28 14:07 被阅读242次

    当需要判断屏幕方向时,我们通常使用UIDevice或者statusBar,但是还有一种方法就是使用陀螺仪来进行判断。上代码:

    初始化motionManager和timer计时器

        let motionManager = CMMotionManager()
        var timer: Timer!
        
            motionManager.startAccelerometerUpdates()
            motionManager.startGyroUpdates()
            motionManager.startMagnetometerUpdates()
            motionManager.startDeviceMotionUpdates()
            
           //注册timer监听
            timer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(ViewController.update), userInfo: nil, repeats: true)
    
    
    

    update函数实现

      
        @objc func update() {
            if let accelerometerData = motionManager.accelerometerData {
                print(accelerometerData)
            }
            if let gyroData = motionManager.gyroData {
                print(gyroData)
            }
            if let magnetometerData = motionManager.magnetometerData {
                print(magnetometerData)
            }
            var result = "unknow"
    
            if let motion = motionManager.deviceMotion {
                //print(deviceMotion)
                let x = motion.gravity.x
                
                let y = motion.gravity.y
                
                if fabs(y) >= fabs(x) {
                    
                    if y >= 0 {
                        result =  "updown"
                        // UIDeviceOrientationPortraitUpsideDown;
                        
                    } else {
                        result =  "updown"
                        // UIDeviceOrientationPortrait;
                        
                    }
                    
                } else {
                    
                    if x >= 0 {
                        result = "right"
                        // UIDeviceOrientationLandscapeRight;
                        
                    } else {
                        result = "left"
                        // UIDeviceOrientationLandscapeLeft;
                        
                    }
                    
                }
                print(result)
            }
        }
    

    相关文章

      网友评论

          本文标题:iOS使用陀螺仪判断屏幕方向

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