UIAlertView不工作在Swift中

当我迅速将这段代码弄糟,我不知道为什么应用程序终止在“alertView.show()”部分显示一个断点,有人请帮助我。

var alertView = UIAlertView( title: "Hey", message: "Hello", delegate: self, cancelButtonTitle: "Cancel" ) alertView.show() 

来自Xcode 6.0 UIAlertView类:

UIAlertView已被弃用。 相反,使用UIAlertController和UIAlertControllerStyleAlert的preferredStyle。

在swift(iOS 8和OS X 10.10)上,你可以这样做:

 var alert = UIAlertController(title: "Alert Title", message: "Alert Message", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Cancel, handler:handleCancel)) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler:{ (ACTION :UIAlertAction!)in println("User click Ok button") })) self.presentViewController(alert, animated: true, completion: nil) func handleCancel(alertView: UIAlertAction!) { println("User click cancel button") } 

如果您想在“ActionSheet”中使用,而不是“Alert”,则只需更改UIAlertControllerStyle,例如:

 var alert = UIAlertController(title: "Alert Title", message: "Alert Message", preferredStyle: UIAlertControllerStyle.ActionSheet) 

UIAlertView在iOS 8中已被弃用,但Swift支持iOS7,并且不能在iOS 7上使用UIAlertController。添加以下方法来解决问题:

 func showAlert(title:NSString, message:NSString,owner:UIViewController) { if let gotModernAlert: AnyClass = NSClassFromString("UIAlertController") { var alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) owner.presentViewController(alert, animated: true, completion: nil) } else { let alertView = UIAlertView(title: title, message: message, delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "OK") alertView.alertViewStyle = .Default alertView.show() } } 

并从这样的代码中的任何地方调用方法:

 showAlert(APP_NAME,message: "Add your alert message here" ,owner: self) 

对我来说最好的办法是…

 class ViewController: UIViewController, UIAlertViewDelegate { var allarme = UIAlertView(title: "Warning", message: "This is a best way to create a alarm message", delegate: self, cancelButtonTitle: "OK") allarme.show() 

记得在类UIAlertViewDelegate上导入

使用以下方法:

 var altMessage = UIAlertController(title: "Warning", message: "This is Alert Message", preferredStyle: UIAlertControllerStyle.Alert) altMessage.addAction(UIAlertAction(title: "Done", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(altMessage, animated: true, completion: nil)