[IOS开发]重力感应判断屏幕状态-OC

来源:互联网 发布:vb创意小程序 编辑:程序博客网 时间:2024/05/18 16:18

@import CoreMotion;


@property (nonatomic,strong)CMMotionManager *motionManager;



-(void)starMotionManager{

    if (_motionManager == nil) {

        _motionManager = [CMMotionManager new];

    }

    if (_motionManager.deviceMotionAvailable) {

        [_motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueuewithHandler:^(CMDeviceMotion * _Nullable motion, NSError * _Nullable error) {

            [self handleDeviceMotion:motion];

        }];

    }

}

-(void)handleDeviceMotion:(CMDeviceMotion *)motion{

    double x = motion.gravity.x;

    double y = motion.gravity.y;

    if (fabs(y)>=fabs(x)) {

        if (y>=0) {

            // UIDeviceOrientationPortraitUpsideDown

            NSLog(@"头向下");

        }else{

            // UIDeviceOrientationPortrait

            NSLog(@"竖屏");

        }

    }else{

        if (x >= 0) {

            // UIDeviceOrientationLandscapeRight

            NSLog(@"头向右");

        }else{

            // UIDeviceOrientationLandscapeLef

            NSLog(@"头向左");

        }

    }

}

// 在适当的位置启动重力引擎

   [self starMotionManager];

// 停止重力引擎

   [self.motionManager stopDeviceMotionUpdates];


原创粉丝点击