iOS-重力感应

本文首发地址
iOS-重力感应
话不多说,开始上代码(这里是最新的)

1.导入头文件

#import  

2.定义变量

@property (nonatomic, strong) CMMotionManager *motionManager;

3.实例化

-(CMMotionManager *)motionManager {
    if (_motionManager == nil) {
        _motionManager = [[CMMotionManager alloc] init];
    }
    return _motionManager;
}

4:定义停止陀螺仪选装的方法

- (void)stopUpdate
{
    if ([self.motionManager isAccelerometerActive] == YES)
    {
        [self.motionManager stopAccelerometerUpdates];
    }
}

5:在VCdealloc的时候记住

- (void)dealloc
{
    _motionManager = nil;
}

6:开始监听手机屏幕变化

- (void)startUpdateAccelerometerResult{
    if ([self.motionManager isAccelerometerAvailable] == YES) {
        [self.motionManager setAccelerometerUpdateInterval:0.06];
        [self.motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error)
         {
             double x = accelerometerData.acceleration.x;
             double y = accelerometerData.acceleration.y;
             if (fabs(y) >= fabs(x))
             {
                 if (y >= 1){
                     //Down
                     NSLog(@"Down");
                 }
                 if(y<= -1){
                     //Portrait
                     NSLog(@"Portrait");
                 }
             }
             else
             {
                 if (x >= 1){
                     //Right
                     NSLog(@"Right");
                     self.btnClick.backgroundColor =[UIColor blueColor];
                     
                 }
                 if(x<= -1){
                     //Left
                     NSLog(@"Left");
                     self.btnClick.backgroundColor =[UIColor yellowColor];
                 }
             }
         }];
    }
}

这里只要把startUpdateAccelerometerResultviewdidload中执行就可以了

于是乎 这里就是最新的检查手机旋转的了。

如有问题可添加我的QQ:1290925041
还可添加QQ群:234812704(洲洲哥学院)
欢迎各位一块学习,提高逼格!
也可以添加洲洲哥的微信公众号

更多消息

更多信iOS开发信息 请以关注洲洲哥 的微信公众号,不定期有干货推送:

iOS-重力感应_第1张图片
这里写图片描述

你可能感兴趣的:(iOS-重力感应)