刚在做一个在iOS设备上实现摇晃进而触发一些体验的功能,现在网上大概搜了一下,然后看了一下开发文档,一个感触是,网上劣质文章太多了,盲目转载拷贝的文章也很多,重样而且还都没有讲清实现原理,与其去网上费时搜,还不如看一下开发文档,很快就可以解决需要解决的问题。
官方开发文档:http://developer.apple.com/library/ios/#documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/motion_event_basics/motion_event_basics.html#//apple_ref/doc/uid/TP40009541-CH6-SW2
具体实现方法:
iOS的SDK中已经将shake 事件很方便的融合进去,就像触发touch事件一样,需要注意的是,先给当前ViewController设置为第一响应者,然后当app发生shake事件后程序会自动执行
-(void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
只需要在相应的触发事件中写需求相应的功能。
具体代码:
设置第一响应者:
-(BOOL)canBecomeFirstResponder{return YES;
}-(void)viewDidAppear:(BOOL)animated{[self canBecomeFirstResponder];
}
处理相应触发事件:
#pragma mark -
#pragma mark - MotionShake Event
-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{}-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{if(motion == UIEventSubtypeMotionShake){NSLog(@"Shake!!!!!!!!!!!");}
}-(void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event{}