iOS-重力感应

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

1.导入头文件

#import <CoreMotion/CoreMotion.h>

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中执行就可以了

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

欢迎各位一块学习,提高逼格!

也可以添加洲洲哥的微信公众号

更多消息

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

 
这里写图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值