【问题标题】:Why attempting to dismiss UIAlertController too early does not dismiss the Alert为什么试图过早解除 UIAlertController 不会解除警报
【发布时间】:2017-12-13 20:31:22
【问题描述】:

我刚刚意识到,过早在警报控制器上调用解除会导致它们不会被解除。例如,如果我呈现警报控制器,然后立即尝试将其关闭,则忽略该关闭。例如

// 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 不会被解除。就我而言,我的解雇通常在警报控制器出现后约 0.5 秒内被调用,并且没有被解雇。我必须像这样手动延迟关闭代码才能使其工作。

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

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

【问题讨论】:

  • 您有什么理由提出并立即解除警报?一种可能的解决方案是创建一个自定义 UIAlertController,它会在 viewDidLoad 方法中自行关闭。
  • 您可以尝试在完成块中关闭它
  • 当我进入活动时会显示警报并保持活动状态,直到我收到蓝牙连接已建立的通知。建立蓝牙通信有时需要 0.5 到 4 秒。这就是为什么有时会快速发出解雇呼叫的原因。

标签: ios


【解决方案1】:

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

present(alertController, animated: true, completion: { 
    alertController.dismiss(animated: true, completion: nil)
})

【讨论】:

    猜你喜欢
    • 2018-06-08
    • 1970-01-01
    • 2017-03-17
    • 2017-09-04
    • 1970-01-01
    • 1970-01-01
    • 2014-10-26
    • 1970-01-01
    • 2012-07-26
    相关资源
    最近更新 更多