Detect Shake Gestures iOS Tutorial

iOS devices have the ability to detect shake gestures. In this tutorial we will show how to detect a shake gesture, and when detected a label text will be updated. This tutorial is made with Xcode 8.3 and built for iOS 10.3

Project Setup

Open Xcode and create a new Single View Application.

For product name, use iOS10ShakeGestureTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.

Go to the Storyboard, drag a Label from the Object Library to the View Controller inside the Storyboard. Double-click the Label and give it a title of "Shake me". Select the Label and select the Auto Layout align button. Select the "Horizontally in Container" checkbox and click "Add 1 Constraint".

auto-layout-horizontally-in-container

Select the Label and select the Auto Layout pin button. Pin the label to the top and and click "Add 1 Constraint".

auto-layout-pin-to-top

The storyboard should look like this.

Open the Assistant Editor and make sure the ViewController.swift file is visible. Ctrl + drag from the Label to the ViewController class and create the following Outlet

Go to the ViewController.swift file. First we need to make the View Controller respond to touch events. It can be achieved by making the View Controller FirstResponder. add the following method.

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

Next, the actual shake can be detected, add the motionEnded(_:with:) method

override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
    if motion == .motionShake {
        shakeLabel.text = "Shaken, not stirred"
    }
}

If the motion is an Shake Gesture, then the Label text is updated. Build and Run the project and shake the device. Note with the iOS Simulator you can select the Shake Gesture in the Hardware menu.

You can download the source code of the iOS10ShakeGestureTutorial at the ioscreator repository on Github.