swift - 如何使警报只出现一次

标签 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)
}

最佳答案

只需创建一个 bool 型全局变量。如果打开该应用程序,它会从 false 开始。然后,一旦看到免责声明,它就会将变量设置为 true。然后根据变量的值呈现View Controller。

    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)
    }
    }
    }

关于swift - 如何使警报只出现一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36849604/

相关文章:

Swift Parse 将 MapView 中的注释保存为 PFGeoPoint

arrays - 如何知道一组一定数量的字符串是否在 2 个数组中匹配

ios - UIAlertController 中的自定义 View

ios8 - 在 iOS8 iPad 上呈现弹出 Controller 时出现 UIViewAlertForUnsatisfiableConstraints

ipad - iPad 上显示的 UIDocumentMenuViewController 给出 "Unable to simultaneously satisfy constraints"

ios - 在带有 Objective-C 的 Xcode 8 中使用 UIAlertController

ios - 如何更改 objective-c 中的字体样式和颜色或操作表?

swift - Swift 中的简单数学运算无法正常工作

ios - 删除插入分组 UITableView 上方的空间

ios - 基于另一个 UIpickerview 的 didSelectRow 返回 UIPickerview 中的 numberOfRowsInComponent 和 titleForRow