900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > iOS之重力感应

iOS之重力感应

时间:2022-08-28 04:17:30

相关推荐

iOS之重力感应

第一次学习重力感应,试着写了一个小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;

}

至此完成,大家运行试试!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。