我刚刚意识到,过早地调用警告 Controller 的 dismiss 会导致它们无法被解雇。例如,如果我显示警报 Controller 然后立即尝试关闭它,则关闭会被忽略。例如
// Done in viewDidLoad
let alertController = UIAlertController(title: nil, message: "Connecting to Bubble Centerpiece...\n\n", preferredStyle: .alert)
present(alertController, animated: true, completion: nil)
alertController.dismiss(animated: true, completion: nil)
使用这段代码,AlertController 不会被解除。在我的例子中,我的解雇通常是在警报 Controller 出现后大约 0.5 秒内被调用并且它没有被解雇。我必须像这样手动延迟解雇代码才能使其正常工作。
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: { self.alertController.dismiss(animated: true, completion: nil)})
我的假设是警报 Controller 需要一些时间才能正确设置,如果关闭调用比警报实际显示早到达,那么它不会被关闭。我想知道是否有更优雅的解决方案,而不是仅仅使用 DispatchQueue 延迟它。
最佳答案
因为,只要您传递 animated: true
,警报 Controller 将不会在层次结构中,直到它完成动画,所以在那之前您不能关闭它。这正是 completion
block 的用途(通常,任何发生异步的好 API 都会为您提供一个完成 block ,让您知道该操作何时完成) .您可以在演示后立即解雇(尽管我认为这不是一个有值(value)的现实生活用例):
present(alertController, animated: true, completion: {
alertController.dismiss(animated: true, completion: nil)
})
关于ios - 为什么过早尝试关闭 UIAlertController 不会关闭警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47801653/