为什么尝试过早关闭 UIAlertController 不会关闭警报

Sai*_*aik 1 ios

我刚刚意识到过早调用警报控制器的解雇会导致他们不会被解雇。例如,如果我呈现警报控制器,然后立即尝试关闭它,则只是忽略了关闭。例如

// 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)
Run Code Online (Sandbox Code Playgroud)

使用此代码,AlertController 不会被解除。就我而言,我的解雇通常在警报控制器出现后大约 0.5 秒内被调用,并且没有被解雇。我不得不像这样手动延迟解除代码以使其工作。

DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: { self.alertController.dismiss(animated: true, completion: nil)})
Run Code Online (Sandbox Code Playgroud)

我的假设是警报控制器需要一些时间才能正确设置,如果解除调用早于警报实际显示到达,则不会被解除。我想知道是否有更优雅的解决方案,而不仅仅是使用 DispatchQueue 延迟它。

Con*_*nor 5

因为,只要您通过animated: true,警报控制器在完成动画之前不会在层次结构中,所以在此之前您不能关闭它。这正是该completion块的用途(通常,任何异步发生的好的 API都会为您提供一个完成块,让您知道该操作何时完成)。您可以在演示后立即关闭(尽管我不认为这是一个有价值的现实生活用例),请执行以下操作:

present(alertController, animated: true, completion: { 
    alertController.dismiss(animated: true, completion: nil)
})
Run Code Online (Sandbox Code Playgroud)