Detect shake gesture IOS Swift

后端 未结 8 2167
难免孤独
难免孤独 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.

提交回复
热议问题