UIResponder 中存在以下三個方法,正是用來處理搖一搖(shake)手勢的:
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event;
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event;
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event;
使用方式很簡單,只要讓該 Controller 支援搖動,並成為第一響應者即可:
- (void)viewDidLoad
{
[super viewDidLoad];
[[UIApplication sharedApplication] setApplicationSupportsShakeToEdit:YES];
[self becomeFirstResponder];
}
接著實作上述方法即可:
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
// 偵測到搖動
}
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
// 搖動取消
}
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
// 搖動結束
if (event.subtype == UIEventSubtypeMotionShake) {
// 在這裡處理搖一搖後的行為
}
}