iOS device orientation disregarding orientation lo

2019-01-06 12:42发布

I want to query the orientation the iPhone is currently in. Using

[UIDevice currentDevice].orientation

works as long as the device isn't orientation-locked. If it is locked, however, it always responds with the locked orientation, not with the actual orientation of the device.

Is there a high-level way to get the actual device orientation?

8条回答
Animai°情兽
2楼-- · 2019-01-06 13:13

The UIAccelerometer class continues to function when the device orientation is locked. You'll have to work out your own methods of turning its variables into orientation values, but it shouldn't be especially complicated.

Have a play with Apple's AcceleromoterGraph sample app to see what values the accelerometer outputs in different orientations.

查看更多
一夜七次
3楼-- · 2019-01-06 13:15

my solution using coremotion,it work even when the device has his orientation locked.

    let motionManager: CMMotionManager = CMMotionManager()

on the did load method

motionManager.deviceMotionUpdateInterval = 0.01
    if motionManager.accelerometerAvailable{
        let queue = NSOperationQueue()
        motionManager.startAccelerometerUpdatesToQueue(queue, withHandler:
            {data, error in

                guard let data = data else{
                    return
                }
                let angle = (atan2(data.acceleration.y,data.acceleration.x))*180/M_PI;

                print(angle)
                if(fabs(angle)<=45){
                    self.orientation = AVCaptureVideoOrientation.LandscapeLeft
                    print("landscape left")
                }else if((fabs(angle)>45)&&(fabs(angle)<135)){

                    if(angle>0){
                        self.orientation = AVCaptureVideoOrientation.PortraitUpsideDown
                        print("portrait upside Down")


                    }else{
                        self.orientation = AVCaptureVideoOrientation.Portrait
                        print("portrait")

                    }
                }else{
                    self.orientation = AVCaptureVideoOrientation.LandscapeRight
                    print("landscape right")

                }


            }
        )
    } else {
        print("Accelerometer is not available")
    }

hope it helps.

查看更多
登录 后发表回答