
- Swift Tutorial
- Swift - Home
- Swift - Overview
- Swift - Environment
- Swift - Basic Syntax
- Swift - Data Types
- Swift - Variables
- Swift - Optionals
- Swift - Tuples
- Swift - Constants
- Swift - Literals
- Swift - Operators
- Swift - Decision Making
- Swift - Loops
- Swift - Strings
- Swift - Characters
- Swift - Arrays
- Swift - Sets
- Swift - Dictionaries
- Swift - Functions
- Swift - Closures
- Swift - Enumerations
- Swift - Structures
- Swift - Classes
- Swift - Properties
- Swift - Methods
- Swift - Subscripts
- Swift - Inheritance
- Swift - Initialization
- Swift - Deinitialization
- Swift - ARC Overview
- Swift - Optional Chaining
- Swift - Type Casting
- Swift - Extensions
- Swift - Protocols
- Swift - Generics
- Swift - Access Control
- Swift Useful Resources
- Swift - Compile Online
- Swift - Quick Guide
- Swift - Useful Resources
- Swift - Discussion
How to detect shake gesture using Swift?
To detect a shake gesture in iOS UIKit provides three different methods, let’s see them one by one.
Method 1 − When the shake gesture begins.
override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { // code you want to implement }
Method 2 − When the shake gesture ends.
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { // Code you want to implement. }
Method 3 − when the shake gesture is cancelled.
override func motionCancelled(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { // code you want to implement. }
Now let’s add some code in our motionBegan method,
override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { print(motion) if motion == .motionShake { print("shake was detected") } }
Also add “self.becomeFirstResponder()” in your viewDidLoad() method. When we run the above code on simulator, and use debug to produce a shake gesture, below is the result that’s produced. We can modify the code above according to our use and perform different operations In our app.
- Related Articles
- How to detect shake events in Kotlin?
- How to detect shake event in Android app?
- How to detect swipe vertically on a ScrollView using Swift?
- How to use Swift to detect when AVPlayer video ends playing?
- How to get fling gesture detection working in an Android App using Kotlin?
- Detect current device with UIUserInterfaceIdiom in Swift
- PHP – How to detect character encoding using mb_detect_encoding()
- How to detect license plates using OpenCV Python?
- How to shake/wiggle an image with CSS?
- How to get fling gesture detection working in an android app?
- How to detect pressing Enter on keyboard using jQuery?
- How to detect Ctrl+Enter in textarea using jQuery?
- How to detect multicollinearity in categorical variables using R?
- How to detect the color using OpenCV in C++?
- How to detect the eye in OpenCV using C++?

Advertisements