如何使用UIAlertController展示警告信息

4

我正在尝试使用Swift弹出警告信息。 这是我在viewDidLoad中使用的代码,但当运行代码时没有任何反应。 有人能帮忙吗?

    var alert = UIAlertController(title: "test title",
        message: "test message",
        preferredStyle: .Alert)
    self.presentViewController(alert, animated: true, completion:nil)

如果您的视图已经在导航堆栈中,那么可以在您的视图中呈现一个视图控制器... - holex
2个回答

17

必须在父视图已经出现之后才能呈现任何视图控制器。将您的呈现代码放置到viewDidApear方法中。

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

        var alert = UIAlertController(title: "test title",
            message: "test message",
            preferredStyle: .alert)
        self.present(alert, animated: true, completion:nil)

    }

3
在iOS8中使用Swift显示警报窗口
func showAlertVIew(){

        var alert = UIAlertController(title: "Info", message: "Welcome to Swift world.", preferredStyle: UIAlertControllerStyle.Alert)

        let alertOKAction=UIAlertAction(title:"OK", style: UIAlertActionStyle.Default,handler: { action in
            println("OK Button Pressed")
            })

        let alertCancelAction=UIAlertAction(title:"Cancel", style: UIAlertActionStyle.Destructive,handler: { action in
            println("Cancel Button Pressed")
         })

        alert.addAction(alertOKAction)
        alert.addAction(alertCancelAction)

        self.presentViewController(alert, animated: true, completion: nil)
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接