ios swift中的警报错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24108739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Alert error in swift
提问by rickdecard
I writing this code in swift and Xcode 6
我用 swift 和 Xcode 6 编写这段代码
@IBAction func Alert(sender : UIButton) {
var alert : UIAlertView = UIAlertView(title: "Hey", message: "This is one Alert", delegate: nil, cancelButtonTitle: "Working!!")
alert.show()
}
Xcode doesn't show error in compilation.
Xcode 在编译时不显示错误。
but in Simulator the APP fails and return the error:
但在模拟器中,APP 失败并返回错误:
(lldb)
thread 1 EXC_BAD_ACCESS(code 1 address=0x20)
回答by GayleDDS
There is a bug in the Swift shim of the UIAlertView convenience initializer, you need to use the plain initializer
UIAlertView 便利初始化器的 Swift shim 中存在一个错误,您需要使用普通初始化器
let alert = UIAlertView()
alert.title = "Hey"
alert.message = "This is one Alert"
alert.addButtonWithTitle("Working!!")
alert.show()
This style code feels more true to the Swift Language. The convenience initializer seems more Objective-C'ish to me. Just my opinion.
这种风格的代码感觉更适合 Swift 语言。便利初始化程序对我来说似乎更像 Objective-C。只是我的观点。
Note: UIAlertView is deprecated(see declaration) but Swift supports iOS7 and you can not use UIAlertController on iOS 7
注意:不推荐使用UIAlertView (请参阅声明)但 Swift 支持 iOS7,您不能在 iOS 7 上使用 UIAlertController
View of UIAlertView Declaration in Xcode
Xcode 中 UIAlertView 声明的视图
// UIAlertView is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead
class UIAlertView : UIView {
An Alert in Swift iOS 8 Only
仅适用于 Swift iOS 8 的警报
var alert = UIAlertController(title: "Hey", message: "This is one Alert", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Working!!", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
Update for Swift 4.2
Swift 4.2 更新
let alert = UIAlertController(title: "Hey", message: "This is one Alert", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Working!!", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)