在 UIAlertController 被解除后执行 segue [英] Perform segue after UIAlertController is dismissed
问题描述
我过去在使用 UIAlertController
时遇到过类似问题,因为在解除 UIAlertController
后,UI 线程总是会出现延迟.
我现在的问题是,如果用户单击好的"UIAlertAction
,我想执行 segue,如果按下取消"UIAlertAction
,则什么也不会发生.
这是我的代码:
I've had similar problems in the past with UIAlertController
in the sense that there's always a lag on the UI thread after the UIAlertController
is dismissed.
My problem right now is that I want to perform a segue if the user clicks on the "Okay" UIAlertAction
and nothing happens if "Cancel" UIAlertAction
is pressed.
This is my code:
// 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
被解除后,如何开始转场?
What is currently happening is when I tap "Okay" the segue is performing, but I can only see the last moments of the transition (i.e the animation starts while the UIAlertController
is being dismissed).
How do I make the segue start once the UIAlertController
is dismissed?
注意 - 如果有另一种方法,我不喜欢用像在固定延迟后执行转场这样的黑客方法来解决这个问题.
谢谢!
推荐答案
问题出在这段代码中:
let okay = UIAlertAction(title: "Yes, please.", style: .default, handler: {_ in
self.performSegue(withIdentifier: "segue", sender: nil)
})
handler:
不是 completion 处理程序.它在警报被(自动)解除之前运行.因此,当警报仍然存在时,您正在启动 segue.
The handler:
is not a completion handler. It runs before the alert is (automatically) dismissed. Thus, you are starting the segue while the alert is still present.
如果您不想使用 delay
(尽管我认为这种方法没有任何问题),我会尝试的是:
If you prefer not to use delay
(though I see nothing wrong with that approach), what I would try is this:
let okay = UIAlertAction(title: "Yes, please.", style: .default, handler: {_ in
CATransaction.setCompletionBlock({
self.performSegue(withIdentifier: "segue", sender: nil)
})
})
这篇关于在 UIAlertController 被解除后执行 segue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!