iOS中检测当前设备的旋转方向(关闭屏幕旋转)

首先添加CoreMotion.frameWork 框架

在代码中配置基本的信息

#import 

// 创始化状态,添加Queue来检测状态
- (void)startMotionManager{
    if (_cmotionManager == nil) {
        _cmotionManager = [[CMMotionManager alloc] init];
    }
    _cmotionManager.deviceMotionUpdateInterval = 1/15.0;
    if (_cmotionManager.deviceMotionAvailable) {
        NSLog(@"Device Motion Available");

        [_cmotionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMDeviceMotion * _Nullable motion, NSError * _Nullable error) {
            [self performSelectorOnMainThread:@selector(handleDeviceMotion:) withObject:motion waitUntilDone:YES];

        }];

}}

// 根据陀螺仪检测到当前的状态,判断屏幕的旋转方向

- (void)handleDeviceMotion:(CMDeviceMotion *)deviceMotion{
    double x = deviceMotion.gravity.x;
    double y = deviceMotion.gravity.y;
    if (fabs(y) >= fabs(x))
    {
        if (y >= 0){
         orientation   = UIDeviceOrientationPortraitUpsideDown;
        }
        else{
         orientation=    UIDeviceOrientationPortrait;
        }
    }
    else
    {
        if (x >= 0){
           orientation=  UIDeviceOrientationLandscapeRight;
        }
        else{
           orientation=  UIDeviceOrientationLandscapeLeft;
        }
    }
}

完成之后
// 在dealloc方法中移除监听
-(void)dealloc{
[_cmotionManager stopDeviceMotionUpdates];

}

你可能感兴趣的:(iOS,orientatio,屏幕旋转检测)