bdunagan

Brian Dunagan

February 13 2010
iPhone Tip: Capturing a Shake Event

It’s very easy to detect a shake event in an iPhone app. There are many good posts on StackOverflow about it, but I wanted to consolidate the code into the minimal number of lines. The key is the motionEnded:withEvent: delegate and the view becoming the first responder.

-(BOOL)canBecomeFirstResponder {
    return YES;
}

- (void) viewDidAppear:(BOOL)animated {
	[self becomeFirstResponder];
    [super viewDidAppear:animated];
}

- (void) viewDidDisappear:(BOOL)animated {
	[self resignFirstResponder];
	[super viewDidDisappear:animated];
}

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
	if (event.subtype == UIEventSubtypeMotionShake) {
		// TODO: insert code here.
	}
	[super motionEnded:motion withEvent:event];
}
Obligatory iPad Post iPhone Tip: Rotating UIView
LinkedIn GitHub Email