Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect shake gesture IOS Swift

I'm developing a app with a gesture system, basically if I turn the iPhone to left my app will do a function, if I turn the iPhone to Right, other function, with others gestures.

I don't have idea how to work with that, i'm trying search in google but not work, the result is only touch gesture and not motion gesture.

someone have a tutorial to help me?

like image 267
FelipeRsN Avatar asked Nov 03 '15 15:11

FelipeRsN


People also ask

What is a shake gesture?

Shake your Android phone or tap on the GPS icon to see time- or location-relevant cards, or both, in the SAP Mobile Cards card deck. The shake-gesture feature detects a timestamp (date and time), an address (location), or both, on cards in a card deck.

How to shake emulator iOS?

In the Hardware menu, choose Shake Gesture. That's it. Your shake handler should be called when you do so.


2 Answers

Swift3 ios10:

override func viewDidLoad() {     super.viewDidLoad()     self.becomeFirstResponder() // To get shake gesture }  // We are willing to become first responder to get shake motion override var canBecomeFirstResponder: Bool {     get {         return true     } }  // Enable detection of shake motion override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {     if motion == .motionShake {         print("Why are you shaking me?")     } } 
like image 73
Speedy99 Avatar answered Sep 17 '22 14:09

Speedy99


Super easy to implement:

1) Let iOS know which view controller is the first in the responder chain:

override func viewDidLoad() {     super.viewDidLoad()     self.becomeFirstResponder() }    override func canBecomeFirstResponder() -> Bool {     return true } 

2) Handle the event in some fashion:

override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {     if(event.subtype == UIEventSubtype.MotionShake) {         print("You shook me, now what")     } } 
like image 37
Ryan Dines Avatar answered Sep 20 '22 14:09

Ryan Dines