2014-06-22 69 views
4

我想使用swift显示警报。 这是我从viewDidLoad中使用的代码,但代码运行时没有任何反应。 有人可以帮忙吗?如何使用UIAlertController显示警报

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

您可以在您的视图呈现视图控制器如果你的观点只被已在导航堆栈... – holex

回答

15

您必须在其父视图出现后才显示任何视图控制器。将您的演示文稿代码放到viewDidApear方法中。

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

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

    } 
+0

同意,viewDidLoad中太早运行此代码 – sketchyTech

2

显示AlerView在斯威夫特iOS8上

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