Detect Shake Gesture in IOS8 with Swift

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 built in iOS 8 with Xcode 6.

Open Xcode and create a new Single View Application. For product name, use iOS8SwiftShakeGestureTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Select Swift as Language and make sure Universal 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 ctrl - drag to the top of the view Controller, hold down ctrl and select "Top Space to Top Layout Guide" and "Center Horizontally in Container"

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 canBecomeFirstResponder() -> Bool {
    return true

Next, the actual shake can be detected, add the motionEnded:withEvent method

override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) {
    if motion == .MotionShake {
      self.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 iOS8SwiftShakeGestureTutorial at the ioscreator repository on Github.