How to implement a Shake Gesture in iOS

Shake Gestures are great for “Magic Eight Ball” type apps: the user shakes the device, then looks at the screen and finds some kind of message. Spooky! Apple have implemented it for clearing text input too – something I must admit I never really liked.

To make your device react to a Shake Gesture you need to implement the following code in the View Controller you app displays. We nee to do this for every View Controller that needs to respond to the shake gesture.

- (BOOL)canBecomeFirstResponder {
    return YES;

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (UIEventSubtypeMotionShake) {
        NSLog(@"I'm shaking!");

First the View Controller needs to be able to be the “first responder”. Now that he can, he will receive all kinds of events from the app.

We’re interested in the Motion Event, specifically when it’s finished. You can also check for when it started, which will react as soon as movement is detected (not so good for that Eight Ball App).

Leave a Reply