自动解除UIAlertController

时间:2014-11-28 03:37:49

标签: iphone swift uialertcontroller

我的应用程序有UILongPressGestureRecognizer,当用户触摸屏幕上的两个元素时,会显示UIAlertController的警告。目前,用户必须按OK按钮才能解除警报,但是我想在0.5秒后自动关闭警报,这样用户就不会破坏他与应用的互动。

有没有办法做到这一点?

5 个答案:

答案 0 :(得分:8)

您可以使用GCD的dispatch_after来实现警报视图的自动关闭。

尝试以下代码:

    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秒后自动调用以关闭警报视图。

答案 1 :(得分:3)

我为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的完整,可行的解决方案。

答案 2 :(得分:1)

斯威夫特3:

DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
    alert.dismiss(animated: false, completion: nil)
}

答案 3 :(得分:0)

快速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)
            }
        }

答案 4 :(得分:-2)

    let alert = UIAlertController(title: "Message Title", message: nil, preferredStyle: .alert)
    present(alert, animated: true) {
        sleep(1)
        alert.dismiss(animated: true, completion: nil)
    }
相关问题