当我在Swift中运行此代码时,我不知道为什么应用程序会在“alertView.show()”部分显示断点并终止运行。请有经验的人帮帮我。
var alertView = UIAlertView(
title: "Hey",
message: "Hello",
delegate: self,
cancelButtonTitle: "Cancel"
)
alertView.show()
当我在Swift中运行此代码时,我不知道为什么应用程序会在“alertView.show()”部分显示断点并终止运行。请有经验的人帮帮我。
var alertView = UIAlertView(
title: "Hey",
message: "Hello",
delegate: self,
cancelButtonTitle: "Cancel"
)
alertView.show()
从Xcode 6.0开始,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")
}
如果您想在“操作表”中使用而不是“警报”,只需更改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)
if let tField = textField { self.textField = textField! self.textField.text = "你好,世界" }
}现在你可以在 handleCancel 或 handleOk 闭包中打印用户输入的内容:println(self.textField.text) - Guy Kahlon