[UIDevice currentDevice].orientation
一般情況下可通過以上代碼獲取設備朝向,但是當設備開啟《屏幕旋轉鎖定》開關后則拿不到準確的設備方向了
//通過設備運動監視器來監聽
//初始化
CMMotionManager *motionManager = [[CMMotionManager alloc] init];
//設置更新頻率,默認值為0.01,就算設置為0也是0.01,值越小更新越快
motionManager.deviceMotionUpdateInterval = 0.3;
[motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMDeviceMotion * _Nullable motion, NSError * _Nullable error) {
double x = deviceMotion.gravity.x;
double y = deviceMotion.gravity.y;
if (fabs(y) >= fabs(x)) {
if (y >= 0) {
//UIDeviceOrientationPortraitUpsideDown
}else {
//UIDeviceOrientationPortrait
}
}else {
if (x >= 0) {
//UIDeviceOrientationLandscapeRight
}else {
//UIDeviceOrientationLandscapeLeft
}
}
}];
這里通過監聽設備運動來識別設備朝向,也可通過重力感應來監聽,但重力感應監聽在設備水平拿的時候得到的是 faceUp/faceDown,如果此朝向需求用于攝像頭方向設定還是用以上監聽比較準確