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 10 and built for iOS 12.

Project Setup

Open Xcode and create a new Single View App.

For product name, use iOSShakeGestureTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

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 Resolve Auto Layout Issues button and select Reset to Suggested Constraints.


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: UIEvent.EventSubtype, 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 iOSShakeGestureTutorial at the ioscreator repository on Github.