iOS 的搖一搖可透過 motionBegan:withEvent: 取得。若 App 沒有收到事件,可先確認 view controller 是否能成為 first responder。
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
if (motion == UIEventSubtypeMotionShake) {
NSLog(@"shake detected");
}
}
若需要在多個頁面共用搖一搖事件,可在 AppDelegate 中攔截 motionBegan,再透過 NSNotificationCenter 發送通知;各頁面只需註冊通知並執行對應 action。
[[NSNotificationCenter defaultCenter] postNotificationName:@"shake" object:self];
這種寫法適合全域搖一搖,例如切換背景、刷新資料或觸發全域動畫。