当我在swift中使用此代码时,我不知道为什么应用程序通过在“alertView.show()”部分中显示断点来终止,有人请帮帮我。
var alertView = UIAlertView(
title: "Hey",
message: "Hello",
delegate: self,
cancelButtonTitle: "Cancel"
)
alertView.show()
答案 0 :(得分:17)
来自Xcode 6.0 UIAlertView类:
UIAlertView已弃用。将UIAlertController与preferredStyle一起使用 取而代之的是UIAlertControllerStyleAlert。
在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)
答案 1 :(得分:1)
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)
答案 2 :(得分:0)
对我来说最好的方式是......
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类上导入
答案 3 :(得分:-1)
使用以下方式:
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)