2

我正在尝试在应用首次加载时添加 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按钮内部,它按预期工作。

4

1 回答 1

6

您应该在viewDidAppear:函数中显示警报。要呈现子视图或另一个视图控制器,父视图控制器必须位于视图层次结构中。

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

* 来自文档

因此,您的代码可能如下所示:

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

}
于 2015-06-14T23:01:30.183 回答