在UIAlertController被解雇后执行segue

时间:2016-11-01 19:48:54

标签: swift segue uialertcontroller

我在过去与UIAlertController有类似的问题,因为在UIAlertController被解雇后,UI线程总是存在延迟。 我现在的问题是,如果用户点击" Okay"我想要执行一个segue。 UIAlertAction如果"取消" UIAlertAction被按下了 这是我的代码:

// create the uialertcontroller to display
let alert = UIAlertController(title: "Do you need help?",
                              message: "Would you like to look for a consultant?",
                              preferredStyle: .alert)
// add buttons
let okay = UIAlertAction(title: "Yes, please.", style: .default, handler: {_ in
    self.performSegue(withIdentifier: "segue", sender: nil)
})
let no = UIAlertAction(title: "No, I'm okay.", style: .cancel, handler: nil)
alert.addAction(okay)
alert.addAction(no)
self.present(alert, animated: true, completion: nil)

目前正在发生的事情是当我点击"好的" segue正在执行,但我只能看到过渡的最后时刻(即动画在UIAlertController被解雇时开始)。
一旦UIAlertController被解雇,我该如何启动segue?

注意 - 如果有另一种方法,我宁愿不采用hacky方法解决这个问题,例如在固定延迟后执行segue。

谢谢!

1 个答案:

答案 0 :(得分:5)

问题在于此代码:

let okay = UIAlertAction(title: "Yes, please.", style: .default, handler: {_ in
    self.performSegue(withIdentifier: "segue", sender: nil)
})

handler:不是完成处理程序。它在之前运行警报被(自动)解除。因此,当警报仍然存在时,您将启动segue。

如果您不想使用delay(虽然我认为这种方法没有错),我会尝试的是:

let okay = UIAlertAction(title: "Yes, please.", style: .default, handler: {_ in
    CATransaction.setCompletionBlock({
        self.performSegue(withIdentifier: "segue", sender: nil)
    })
})