第一次学习重力感应,试着写了一个小demo,写的一般,大家互相学习,话不多说,直接上代码!
首先要导入头文件CoreMotion/CoreMotion.h,然后声明CMMotionManager管理类,下面是代码
– (void)stopUpdate
{
if ([self.motionManager isAccelerometerActive] == YES)
{
[self.motionManager stopAccelerometerUpdates];
}
}
– (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){//DownNSLog(@"Down");}if(y<= -1){//PortraitNSLog(@"Portrait");}}else{if (x >= 1){//RightNSLog(@"Right");self.btnClick.backgroundColor =[UIColor blueColor];}if(x<= -1){//LeftNSLog(@"Left");self.btnClick.backgroundColor =[UIColor yellowColor];}}}];}
}
– (void)dealloc
{
_motionManager = nil;
}
至此完成,大家运行试试!