摇晃iPhone的API使用

iOS提供了摇晃事件的API,用起来很方便,当摇动设备的时候,Label的hidden变为NO,平时是YES:

 

 

代码很简单,用motionBegan函数,但是官方文档介绍这个方法的时候有这么句话:

Discussion

iOS informs the first responder only when a motion event starts and when it ends; for example, it doesn’t report individual shakes. The receiving object must be the first responder to receive motion events.

所以需要把当前的视图控制器设置为第一响应者

此外还需要把canBecomeFirstResponder方法设置为YES:

代码:

– (void)viewDidLoad

{

[super viewDidLoad];

[self becomeFirstResponder];

 

// Do any additional setup after loading the view, typically from a nib.

}

-(BOOL)canBecomeFirstResponder {

return YES;

}

 

 

-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{

if (event.type==UIEventSubtypeMotionShake) {

NSLog(@”shake”);

SHAKElABEL.hidden=NO;

}

 

}

-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{

if (motion==UIEventSubtypeMotionShake) {

NSLog(@”no shake”);

SHAKElABEL.hidden=YES;

}

}

 再适当的时候还应该resignFirstResbonser

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注