2016-08-04 44 views
0

此函数在我的viewDidLoad中调用。它没有出现错误,但没有发生任何事情。它肯定会被打电话,因为我告诉它打印和它的工作。无法迅速弹出提醒

这里是警戒代码:屏幕上显示

func makeAlert() 
    { 
     let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: UIAlertControllerStyle.Alert) 
     // Create the actions 
     let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { 
     UIAlertAction in 
     NSLog("OK Pressed") 
     } 
     let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { 
     UIAlertAction in 
     NSLog("Cancel Pressed") 
     } 
     // Add the actions 
     alertController.addAction(okAction) 
     alertController.addAction(cancelAction) 
     // Present the controller 
     self.presentViewController(alertController, animated: true, completion: nil) 
+1

尝试在ViewDidAppear调用makeAlert()。 –

+0

非常感谢 – Steve

+0

很好用,不要在viewDidLoad中放置太多的代码,否则会延迟视图的转换。 –

回答

1

这里的问题是,你正在尝试呈现视图控制器(带有您的viewDidLoad)之前,以显示您alertControllerviewDidLoad()在您的视图控制器加载到内存后调用,而不一定在视图处于视图层次结构中时调用。

因此,呼吁makeAlert()viewDidAppear(_:)

override func viewDidAppear(animated: Bool) { 
    makeAlert() 
} 

这可以确保您的视图控制器已经显示,并能出示您的alertController

阅读有关viewDidLoad()viewDidAppear(_:)这里是有帮助的: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/index.html#//apple_ref/occ/instm/UIViewController/