bdunagan
fill the void

Posted
13 February 2010 @ 12pm

Tagged
development

5 Comments

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];
}

5 Comments

Posted by
Ryan
23 May 2010 @ 6am

Seriously,…. Thanks =)
This is so easy to add to an app, I am so glad Google likes your page…. you’ve saved me a tonne of work.


Posted by
Sebastian
1 June 2010 @ 3pm

Thank you so much !!!
Works just perfect :)


Posted by
bdunagan
1 June 2010 @ 11pm

Glad you both found it useful! :)


Posted by
Moi
23 December 2010 @ 1am

Thank you very much, only place with the complete and easy
to understand answer after an hour of searching!


Posted by
Brian
29 December 2011 @ 6pm

If I may ask, where am I supposed to put this code? I have this problem, I want to shake my device to hide/unhide the toolbars of my app, I have declared the toolbars as IBOutlets and then through using the punctual syntax hidden the toolbars, I have also written a method able to decide whether the toolbars are hidden or not, to be able to decide whether to hide the toolbars or not. I just can’t get the shake gesture to be recognized by my app, and therefore I can’t connect a proper response to the shake gesture.


Leave a Comment