调用 UIAlertController 并等待用户交互

Call UIAlertController and await user interaction

我知道,UIAlertController 是异步工作的。但我正在寻找 "blocking" 解决方案。我的意思是阻塞,在用户点击按钮后应该执行以下代码。

我的 "AlertBox" 非常简单,它被放入一个 "global helper" 文件中,因为我使用了很多这样的 AlertBoxes:

func showAlertBoxWithOK(headline:String, message:String, OkButtonText:String, viewController:UIViewController) {

    let alertController = UIAlertController(title: headline, message: message, preferredStyle:UIAlertControllerStyle.Alert)

    alertController.addAction(UIAlertAction(title: OkButtonText, style: UIAlertActionStyle.Default)
    { action -> Void in
        return
    })
    viewController.presentViewController(alertController, animated: true, completion: {
        return
    })
}

在视图中,我这样称呼它:

println ("this is before the AlertBox")
showAlertBoxWithOK("Sample", "Hello World.", "OK", self)
println ("this is after the AlertBox")

代码来到第 1 行并打印文本。 接下来出现 AlertBox。 但是:现在第 3 行在用户确认警报之前执行。

有没有办法在用户确认 AlertBox 之前停止代码处理?就像 VisualBasic 中非常简单的 "MessageBox" 一样,它会阻塞 UI 和代码?或者可以像 await 在 C# 中那样完成吗?

我的问题是,有一个非常长的代码,有很多要显示的 AlertBoxes...

编辑

假设这是我的代码:

var a = 0
a = a + 5
showAlertBox("5 reached" ...)
a = a + 10
a = a + 15
showAlertBox("30 reached" ...)
a = a + 20
a = a + 25
showAlertBox("75 reached" ...)

等等。我不希望代码向前推进,同时显示 AlertBox。并且由于计算(为简化起见,用 a = ... 进行了说明),很难将所有代码分成块。

与其将所有代码都放在同一个方法中,不如将您希望在用户交互后执行的代码放入另一个方法中。然后,当按下 OK 按钮时调用该方法。

例如:

func showAlertBoxWithOK(headline:String, message:String, OkButtonText:String, viewController:UIViewController) {

    a += 5

    let alertController = UIAlertController(title: headline, message: message, preferredStyle:UIAlertControllerStyle.Alert)

    alertController.addAction(UIAlertAction(title: OkButtonText, style: UIAlertActionStyle.Default)
        { action -> Void in
            self.showNextAlertBox("headline2", message: "message2", OkButtonText: "OK", viewController: self)
            return
        })
    viewController.presentViewController(alertController, animated: true, completion: {
        return
    })
}

func showNextAlertBox(headline:String, message:String, OkButtonText:String, viewController:UIViewController) {

    a += 10
    a += 15

    let alertController = UIAlertController(title: headline, message: message, preferredStyle:UIAlertControllerStyle.Alert)

    alertController.addAction(UIAlertAction(title: OkButtonText, style: UIAlertActionStyle.Default)
        { action -> Void in
            return
        })
    viewController.presentViewController(alertController, animated: true, completion: {
        return
    })
}