How to identify iPhone SHAKE in Swift? [duplicate]

浪尽此生 提交于 2019-12-11 14:23:16

问题


Hi I want to identify the iPhone SHAKE when user shakes their phone, either in background mode or in foreground mode of the app.

Please assist me. Thanks in advance.


回答1:


The main trick is that you need to have some UIView (not UIViewController) that you want as firstResponder to receive the shake event messages. Here's the code that you can use in any UIView to get shake events:

class ShakingView: UIView {

override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
    if event?.subtype == .motionShake {
        // Put in code here to handle shake
    }
    if super.responds(to: #selector(UIResponder.motionEnded(_:with:))) {
        super.motionEnded(motion, with: event)
    }
}

override var canBecomeFirstResponder: Bool { return true }

You can easily transform any UIView (even system views) into a view that can get the shake event simply by subclassing the view with only these methods (and then selecting this new type instead of the base type in IB, or using it when allocating a view).

In the view controller, you want to set this view to become first responder:

override func viewWillAppear(_ animated: Bool) {
    shakeView.becomeFirstResponder()
    super.viewWillAppear(animated)
}

override func viewWillDisappear(_ animated: Bool) {
   shakeView.resignFirstResponder()
   super.viewWillDisappear(animated)
}

Don't forget that if you have other views that become first responder from user actions (like a search bar or text entry field) you'll also need to restore the shaking view first responder status when the other view resigns!

This method works even if you set applicationSupportsShakeToEdit to NO.

For objective c version refer link How do I detect when someone shakes an iPhone?




回答2:


Try something like this:

override func motionBegan(_ motion: UIEventSubtype, with event: UIEvent?) {
    print("Device was shaken!")
}


来源:https://stackoverflow.com/questions/47448705/how-to-identify-iphone-shake-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!