如何检测用户是否停止在Swift中摇动手机

时间:2019-05-23 08:12:08

标签: ios swift xcode

我想知道用户何时停止摇晃,何时停止摇晃,我想关闭alertViewController。任何帮助将不胜感激。谢谢。

我已经尝试使用motionEnded和motionBegan方法。

这是我的代码。当用户停止摇动手机时,我想关闭alertViewController。

       let alertController = UIAlertController(title: nil, message:
        "Shaking", preferredStyle: UIAlertController.Style.alert)

    override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
        if motion == .motionShake {
            self.present(alertController, animated: true, completion: nil)

        }
    }

    override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
        if alertController.isBeingPresented {
            alertController.dismiss(animated: true, completion: nil)
        }
    }

1 个答案:

答案 0 :(得分:1)

使用以下方法结束运动,有关更多信息,请参见此帖子https://developer.apple.com/documentation/uikit/uiresponder/1621090-motionended

在委托方法之外声明alertController

let alertController = UIAlertController(title: nil, message:
    "Shaking", preferredStyle: UIAlertController.Style.alert)

override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
    if motion == .motionShake && !alertController.isBeingPresented {
        self.present(alertController, animated: true, completion: nil)

    }
}

override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
    if motion == .motionShake {
         alertController.dismiss(animated: true, completion: nil)
    }
}
相关问题