在应用程序启动时显示 UIAlertView
Display an UIAlertView when app launches
我正在尝试在应用首次加载时添加 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
内部用于按钮,它按预期工作。
您应该在 viewDidAppear:
函数中显示警报。要呈现子视图或另一个视图控制器,父视图控制器必须位于视图层次结构中。
The viewDidAppear
function "notifies the view controller that its view was added to a view hierarchy."
* From the 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)
}
}
我正在尝试在应用首次加载时添加 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
内部用于按钮,它按预期工作。
您应该在 viewDidAppear:
函数中显示警报。要呈现子视图或另一个视图控制器,父视图控制器必须位于视图层次结构中。
The
viewDidAppear
function "notifies the view controller that its view was added to a view hierarchy."* From the 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)
}
}