Detect shake gesture in Swift

In my opinion, one of the most underrated iOS gesture is the shake’y one. To shake your phone is a natural hand movement. As I was young, the dictum „Shake to {verb}“ was very common. iOS makes it unbelievable easy to listen or react to this event. I used this to implement Nomster’s „Shake to decide“-feature.

I used the built in event handler motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) of iOS 2 and later (Apple Developer reference). This method will be raised in case of a detected motion has ended. We can identify the type of the gesture by using the enum UIEventSubtype values. The method is inherited by the NSObject.

After this two lines of code, you can add any additional control flow you want to this method. In case of Nomster, I put a simple random bot into it.

override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) {
        if motion == .MotionShake {
            // Do what you want
        }
}

If you have multiple respond-able classes, you have to override the method:

override func canBecomeFirstResponder() -> Bool {
    return true
}

You can see the code in action in Nomster’s ’shake to decide‘-feature. Related file: DiceViewController.swift

Schreibe einen Kommentar

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit Deinem WordPress.com-Konto. Abmelden / Ändern )

Twitter-Bild

Du kommentierst mit Deinem Twitter-Konto. Abmelden / Ändern )

Facebook-Foto

Du kommentierst mit Deinem Facebook-Konto. Abmelden / Ändern )

Google+ Foto

Du kommentierst mit Deinem Google+-Konto. Abmelden / Ändern )

Verbinde mit %s