2016-04-25 72 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