如何在Swift中识别iPhone SHAKE?

How to identify iPhone SHAKE in Swift?

您好,我想识别 iPhone 当用户摇动 phone 时,无论是在应用程序的后台模式还是前台模式下。

请帮助我。 提前致谢。

尝试这样的事情:

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

主要技巧是您需要一些 UIView(不是 UIViewController)作为 firstResponder 来接收摇动事件消息。以下是您可以在任何 UIView 中使用以获取摇动事件的代码:

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 }

您可以轻松地将任何 UIView(甚至系统视图)转换为可以获取摇动事件的视图,只需通过仅使用这些方法对视图进行子类化(然后选择这种新类型而不是 IB 中的基类型,或者在分配视图时使用它)。

在视图控制器中,您想将此视图设置为第一响应者:

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

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

不要忘记,如果您有其他视图从用户操作(如搜索栏或文本输入字段)成为第一响应者,您还需要在其他视图退出时恢复摇晃视图第一响应者状态!

即使您将 applicationSupportsShakeToEdit 设置为 NO,此方法也有效。

objective c版本参考linkHow do I detect when someone shakes an iPhone?