Intercepting Motion Events(捕捉摇晃事件)
视频锁定
{$ currentTime | date:'mm:ss' $}
{$ timeLeft | date:'mm:ss' $}
大多数哺乳动物的内耳是非常厉害的,它可以检测到身体的运动、加速度、转身等等,然后将这些转化成信号传递给大脑,再由大脑传递到身体的其他部位。
同样的,在iPhone中,也有两个内置的传感器: 一个称为”加速器”,它是用来检测速度和加速度的; 另一个称为”陀螺仪”,它是用来检测的。 这些传感器不停的捕捉到这些事件,当然,我们的App也可以捕捉到这些事件,然后针对这些事件做一些事情。
让我们回到水晶球应用,如果我们简单的做一个点击按钮的时候,出现一个随机的预言结果,就失去了很大的乐趣。如果我们换一种方式呢?比如当我们摇晃手机的时候,随机产生出一个预测的结果,那么是一件多么有意思的事情啊!
我们打开水晶球的应用,点击ViewController.m
,在类的最下方,@end之前,加入如下代码:
-(BOOL)canBecomeFirstResponder{
//真或者假 true or false YES NO 0 1
return YES; //defalut NO
}
-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{
//NSLog(@"motionBegan");
predictionLabel.text=@"";
}
-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{
if(motion==UIEventSubtypeMotionShake){
//NSLog(@"motionEnded");
NSInteger indexofPredictionArray= arc4random_uniform([self.predictionArray count]);
predictionLabel.text =[self.predictionArray objectAtIndex:indexofPredictionArray];
}
}
-(void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event{
NSLog(@"motionCancelled");
}
在线练习
{$ activeFileHint $}