【发布时间】:2014-11-28 03:37:48
【问题描述】:
我的应用程序有一个UILongPressGestureRecognizer,当用户触摸屏幕上的两个元素时,它会显示带有UIAlertController 的警报。目前,用户必须按 OK 按钮才能解除警报,但我希望在 0.5 秒后自动解除警报,这样用户就不会影响他与应用程序的交互。
有什么办法吗?
【问题讨论】:
标签: iphone swift uialertcontroller
我的应用程序有一个UILongPressGestureRecognizer,当用户触摸屏幕上的两个元素时,它会显示带有UIAlertController 的警报。目前,用户必须按 OK 按钮才能解除警报,但我希望在 0.5 秒后自动解除警报,这样用户就不会影响他与应用程序的交互。
有什么办法吗?
【问题讨论】:
标签: iphone swift uialertcontroller
使用GCD的dispatch_after可以实现alert view的自动关闭
试试下面的代码:
let delay = 0.5 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue()) { () -> Void in
self.dismissPopover()
}
这里,dismissCategoryPopover() 是一个自定义方法,将在 0.5 秒后自动调用以关闭警报视图。
【讨论】:
我为 Swift 2.1 更新了一个自定义函数,它使用 UIAlertController 来模拟 Android 中的 Toast 功能。
func showToast(withMessage message:String) {
let menu = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
let cancel = UIAlertAction(title: message, style: .Cancel, handler: nil)
menu.addAction(cancel)
self.presentViewController(menu, animated: true, completion: nil)
let delay = 1.5 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
self.tableView.setEditing(false, animated: true)
dispatch_after(time, dispatch_get_main_queue()) { () -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
}
}
这显示了 OP 的完整、有效的解决方案。
【讨论】:
斯威夫特 3:
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
alert.dismiss(animated: false, completion: nil)
}
【讨论】:
斯威夫特 5
呈现UIAlertController 并在完成块中,在指定时间后将其关闭。
默认情况下,完成块中的任何代码都在不同的线程上运行,因此,获取主线程并关闭 UIAlertController
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
present(alertController, animated: true) {
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
alertController.dismiss(animated: true, completion: nil)
}
}
【讨论】:
let alert = UIAlertController(title: "Message Title", message: nil, preferredStyle: .alert)
present(alert, animated: true) {
sleep(1)
alert.dismiss(animated: true, completion: nil)
}
【讨论】:
sleep 是初学者的错误。你需要忘记这一点。你应该永远像这样使用sleep,它会阻止整个应用程序。请改用适当的延迟。