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 ges
Swift 4, 5
iOS 10+
UIApplication
, UIViewController
, UIView
, and UIWindow
are all UIResponder
objects by default which means they can all handle motion events, like shake, without any special configuration. Therefore, simply override the appropriate motion method:
class YourViewController: UIViewController {
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
if motion == .motionShake {
print("device did shake")
}
}
}
Additionally, you can override motionBegan(_:with:)
and motionCancelled(_:with:)
. And unlike overriding certain touch events, there is no need to call super.
Swift 5
Just add following methods to ViewController and execute the code
override func becomeFirstResponder() -> Bool {
return true
}
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?){
if motion == .motionShake {
print("Shake Gesture Detected")
//show some alert here
}
}