2016-04-25 70 views
2

我想弄明白是如何创建一个弹出窗口,只有当您启动应用程序时才会出现一次,然后不会再次出现,除非您关闭应用程序并重新启动它。但是,如果您查看下面的代码,则会发现每次出现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) 
} 
+0

的可能的复制[UIAlertView中或UiAlertController在夫特只有一次显示](http://stackoverflow.com/questions/28285993/uialertview-or-uialertcontroller-to-display-only-once-in-swift ) – Caleb

回答

5

只需创建一个全局变量即Bool。如果应用程序被打开,它会从错误开始。然后一旦看到免责声明,它将变量设置为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) 
    } 
    } 
    } 
+0

非常感谢你!它工作完美 – Benpeterscode

+0

请将此答案标记为公认的正确解决方案。谢谢, – rMickeyD