【问题标题】:How to detect if user STOPPED shaking the phone in Swift如何检测用户是否停止在 Swift 中摇晃手机
【发布时间】:2019-10-09 18:23:01
【问题描述】:

我想知道用户什么时候停止摇晃,什么时候停止摇晃,我想关闭 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)
        }
    }

【问题讨论】:

  • motionEnded 应该可以完成这项工作。为什么没有成功?
  • 但是如何在motionEnded 中隐藏alertController?
  • alertController 设为属性,以便您可以在两种方法中访问它。
  • @Sweeper 你能写下代码吗?
  • AtulParmar 已经在他的回答中写下了我的意思。

标签: ios swift xcode


【解决方案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)
    }
}

【讨论】:

  • 有效。但过了一会儿,它抛出 SIGBRT 说 Application tried to present modally an active controller <Shake_Gesture_app.ViewController: 0x10217d350>.
  • 使用 ".isBeingPresented" 和 ".isBeingDismissed" 属性来检查 'alertController' 操作系统是否打开并相应地做需要。
  • 在当前的警报控制器上设置条件。
  • 试过你的代码。抛出相同的错误并且 alertController 没有被解除。已经在motionEnded 中尝试了条件alertController.isBeingPreseneted
猜你喜欢
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-18
  • 2010-09-14
  • 1970-01-01
相关资源
最近更新 更多