循环遍历多个UIAlertController

时间:2015-03-11 21:04:52

标签: swift synchronization uialertcontroller

在某些情况下,我的应用程序需要显示多个警报消息。在开始时收集错误消息,并且需要一次一个地向用户显示。当第一个被确认时,应该呈现下一个。问题是,他们都试图同时执行,显然。有同步的智能方法吗?这里有一些代码简单描述了我想要做的事情:

var errors : [NSError]!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let error1 = NSError(domain: "Test1", code: 1, userInfo: [NSLocalizedFailureReasonErrorKey : "Test1 reason."])

    let error2 = NSError(domain: "Test2", code: 2, userInfo: [NSLocalizedFailureReasonErrorKey : "Test2 reason."])

    let error3 = NSError(domain: "Test3", code: 2, userInfo: [NSLocalizedFailureReasonErrorKey : "Test3 reason."])

    errors = [error1, error2, error3]

}

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    for error in errors {

        self.showAlert(error)

    }

}

func showAlert(error: NSError) {

    var alert = UIAlertController(title: error.domain, message: error.localizedDescription, preferredStyle: .Alert)
    alert.addAction(UIAlertAction(title: "OK", style: .Default, handler:nil))

    self.presentViewController(alert, animated: true, completion: nil)
}

1 个答案:

答案 0 :(得分:7)

你快到了。拥有警报消息的缓冲区是正确的想法。但是,不应立即显示所有警报,而应将showAlert()调用移至UIAlertAction的处理程序。因此,如果一个警报被解除,则会显示下一个警报。

这样的事情:

var errors : [NSError]!

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    let error1 = NSError(domain: "Test1", code: 1, userInfo: [NSLocalizedFailureReasonErrorKey : "Test1 reason."])
    let error2 = NSError(domain: "Test2", code: 2, userInfo: [NSLocalizedFailureReasonErrorKey : "Test2 reason."])
    let error3 = NSError(domain: "Test3", code: 2, userInfo: [NSLocalizedFailureReasonErrorKey : "Test3 reason."])

    errors = [error1, error2, error3]

    showError() // show an alert if errors are queued
}

func showError() {
    if let error = errors.first {
        let alert = UIAlertController(title: error.domain, message: error.localizedDescription, preferredStyle: .Alert)
        let okayAction = UIAlertAction(title: "OK", style: .Default) { action in
            self.errors.removeAtIndex(0) // remove the message of the alert we have just dismissed

            self.showError() // show next alert if there are more errors queued
        }
        alert.addAction(okayAction)
        presentViewController(alert, animated: true, completion: nil)
    }
    else {
        println("All alerts shown")
    }
}

建议:解除多个警报非常烦人。也许你可以创建一个专用的全屏viewController,它显示UITableView中的所有错误消息。这当然取决于典型用户将看到的警报消息的数量。如果它经常超过三个我将使用模态UIViewController一目了然地显示所有消息。