剛在做一個在iOS裝置上實現搖晃進而觸發一些體驗的功能,現在網上大概搜了一下,然後看了一下開發文檔,一個感觸是,網上劣質文章太多了,盲目轉載拷貝的文章也很多,重樣而且還都沒有講清實現原理,與其去網上費時搜,還不如看一下開發文檔,很快就可以解決需要解決的問題。 具體實現方法: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只需要在相應的觸發事件中寫需求相應的功能。 具體代碼:設定第一響應者:[cpp] -(BOOL)canBecomeFirstResponder{ return YES; } -(void)viewDidAppear:(BOOL)animated{ [self canBecomeFirstResponder]; } 處理相應觸發事件:[cpp] #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{ }