Detect shake gesture IOS Swift

后端 未结 8 2143
难免孤独
难免孤独 2020-12-08 02:27

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

相关标签:
8条回答
  • 2020-12-08 03:12

    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.

    0 讨论(0)
  • 2020-12-08 03:19

    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
        }
    }
    
    0 讨论(0)
提交回复
热议问题