Detect iOS Shake Gestures: Swift

Shake it off?

Image for post
Image for post
Photo by Quino Al on Unsplash

Shaking is a rare gesture…wait Google use it on Maps to give feedback. It can be used for undo. It’s useful…?

Difficulty: Beginner | Easy | Normal | Challenging

Prerequisites:

Motivation

You want to implement shaking gestures this means you actually want to use a shake gesture for undo or redo.

In this case we are simply going to update a UILabel to show that the device has been shaken n times (beginning at zero).

Image for post
Image for post

We have a single ViewController called ViewController. We create this basic view controller with a shakeCounter property that is displayed on the UILabel.

Image for post
Image for post
Click for Gist

We need to force this to receive touch events. That is, we make ViewController the first ViewController in the responder chain using the instance method becomeFirstResponder()

Image for post
Image for post
Click for Gist

Handle the event using motionEnded(_:with:) within the ViewController. In this case, we are simply going to update the counter and the UILabel.

Image for post
Image for post
Click for Gist

The completed ViewController looks like the following:

Image for post
Image for post
Click for Gist

There is a repo with the full project, if you want to download it.

Conclusion

I hope this article has helped you to implement shake gestures in Swift.

Good stuff.

Extend your knowledge

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store