如何发出警报只出现一次

时间:2016-04-25 19:39:34

标签: swift uialertcontroller

我正在试图弄清楚如何创建一个弹出窗口,该窗口仅在您启动应用程序时出现一次,然后除非您关闭应用程序并重新启动它,否则不会再次出现。但是,如果您查看下面的代码,您会发现每次出现ViewController时都会弹出警报。例如,如果您转到设置标签然后返回主ViewController,则会弹出警告。

override func viewDidAppear(animated: Bool) {
    let alertController = UIAlertController(title: "Disclaimer", message: "WARNING: Please ride carefully!", preferredStyle: UIAlertControllerStyle.Alert)
    alertController.addAction(UIAlertAction(title: "Accept", style: UIAlertActionStyle.Default, handler: nil))
    self.presentViewController(alertController, animated: true, completion: nil)
}

1 个答案:

答案 0 :(得分:6)

只需创建一个Bool的全局变量。如果应用程序已打开,则从false开始。然后,一旦看到免责声明,它就会将变量设置为true。然后根据变量的值显示视图控制器。

    var disclaimerHasBeenDisplayed = false

class ViewController {

     override func viewDidAppear(animated: Bool) {

          if disclaimerHasBeenDisplayed == false {

             disclaimerHasBeenDisplayed = true

             let alertController = UIAlertController(title: "Disclaimer", message: "WARNING: Wakeboarding is fun, however it can be highly dangerous.
     Wake Dice is not liable for any injuries obtained while wakeboarding. Please ride carefully!", preferredStyle: UIAlertControllerStyle.Alert)
     alertController.addAction(UIAlertAction(title: "Accept", style: UIAlertActionStyle.Default,handler: nil))

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