应用启动时显示UIAlertView

时间:2015-06-14 22:53:53

标签: swift swift2

我尝试在应用首次加载时添加UIAlertView或Controller。目前,我的viewDidLoad方法中包含此代码。

let welcomeAlert = UIAlertController(title: "hola", message: "this is a test.", preferredStyle: UIAlertControllerStyle.Alert)
welcomeAlert.addAction(UIAlertAction(title: "ok.", style: UIAlertActionStyle.Default, handler: nil))

self.presentViewController(welcomeAlert, animated: true, completion: nil)

为什么不会显示警报视图?我使用了相同的代码,但是在IBAction内部用于按钮,它按预期工作。

1 个答案:

答案 0 :(得分:6)

您应该在viewDidAppear:功能中显示提醒。要显示子视图或其他视图控制器,父视图控制器必须位于视图层次结构中。

  

viewDidAppear函数“通知视图控制器其视图已添加到视图层次结构中。”

     

*来自documentation

所以,你的代码看起来像这样:

class MyViewController: UIViewController {

    override func viewDidAppear(animated: Bool){
        super.viewDidAppear(animated)

        let welcomeAlert = UIAlertController(title: "hola", message: "this is a test.", preferredStyle: UIAlertControllerStyle.Alert)
        welcomeAlert.addAction(UIAlertAction(title: "ok.", style: UIAlertActionStyle.Default, handler: nil))
        self.presentViewController(welcomeAlert, animated: true, completion: nil)
    }

}