当var遇到某个值时,UialertController只显示一次

时间:2015-06-11 12:39:03

标签: ios swift uialertcontroller

所以我的应用程序的工作方式是你点击一个单元格,var值被修改(例如+1)。当我的var达到某个值(10)时,我已经弄清楚如何让UIalert弹出。但是现在我每次更新var时都会弹出警报。我想要它做的是当var击中10时弹出并在那之后停止

下面是代码:

    if (section1score >= 10){
        let alertController: UIAlertController = UIAlertController(title: NSLocalizedString("Section 1 score is over 10", comment: ""),
            message: " \(message1)",
            preferredStyle: .Alert)

        let OKAction = UIAlertAction(title: "OK", style: .Default) {
            action -> Void in }

        alertController.addAction(OKAction)
        self.presentViewController(alertController, animated: true, completion: nil)

    } 

if (section2score >= 10){
        let alertController: UIAlertController = UIAlertController(title: NSLocalizedString("Section 2 Score is over 10", comment: ""),
            message: "\(message2)",
            preferredStyle: .Alert)

        let OKAction = UIAlertAction(title: "OK", style: .Default) {
            action -> Void in }

        alertController.addAction(OKAction)
        self.presentViewController(alertController, animated: true, completion: nil)

    }

2 个答案:

答案 0 :(得分:1)

设置Bool以检查是否已显示警报。全局创建Bool并最初将其设置为false

var showedAlert = false

func yourFunction() {
    if section1score >= 10 && showedAlert == false {
        // show alert
        showedAlert = true
    }

    if section2score >= 10 && showedAlert == false {
        // show alert
        showedAlert = true
    }
}

Comparison Operators

答案 1 :(得分:1)

您可以使用属性来跟踪您何时显示提醒,以便在您显示提醒后,您又不会再显示该提醒。

var hasShownAlert: Bool = false

if (section1score >= 10 && !hasShownAlert){
    let alertController: UIAlertController = UIAlertController(title: NSLocalizedString("Section 1 score is over 10", comment: ""),
        message: " \(message1)",
        preferredStyle: .Alert)

    let OKAction = UIAlertAction(title: "OK", style: .Default) {
        action -> Void in }

    alertController.addAction(OKAction)
    self.presentViewController(alertController, animated: true, completion: nil)
    hasShownAlert = true
} 

if (section2score >= 10 && !hasShownAlert){
    let alertController: UIAlertController = UIAlertController(title: NSLocalizedString("Section 2 Score is over 10", comment: ""),
        message: "\(message2)",
        preferredStyle: .Alert)

    let OKAction = UIAlertAction(title: "OK", style: .Default) {
        action -> Void in }

    alertController.addAction(OKAction)
    self.presentViewController(alertController, animated: true, completion: nil)
    hasShownAlert = true
}