53

Detect Shake Gestures iOS Tutorial

 5 years ago
source link: https://www.tuicool.com/articles/hit/iUjmeiZ
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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.

Rja2Y3Y.png!web

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.

EJZNjmB.png!web

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.

YJ3myaY.png!web

The storyboard should look like this.

nuyIVvY.png!web

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

Z3iQz2R.png!web

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.

RnAvquE.png!web

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK