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

版权声明:本文为博主原创文章,转载请标明文章来源。 https://blog.csdn.net/SunFlowerInRain/article/details/78847740

首先添加CoreMotion.frameWork 框架

在代码中配置基本的信息

#import <CoreMotion/CoreMotion.h>

// 创始化状态,添加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];

}

猜你喜欢

转载自blog.csdn.net/SunFlowerInRain/article/details/78847740
今日推荐