swift中的警报错误

ric*_*ard 18 ios swift

我在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()
}
Run Code Online (Sandbox Code Playgroud)

Xcode在编译时不显示错误.

但在模拟器中,APP失败并返回错误:

(lldb)
thread 1 EXC_BAD_ACCESS(code 1 address=0x20)
Run Code Online (Sandbox Code Playgroud)

Gay*_*DDS 44

UIAlertView便捷初始化程序的Swift填充程序中存在一个错误,您需要使用普通初始化程序

let alert = UIAlertView()
alert.title = "Hey"
alert.message = "This is  one Alert"
alert.addButtonWithTitle("Working!!")
alert.show()
Run Code Online (Sandbox Code Playgroud)

这种样式代码对Swift语言更为真实.方便初始化程序对我来说似乎更客观.只是我的观点.

注意:UIAlertView已弃用(请参阅声明)但Swift支持iOS7,您不能在iOS 7上使用UIAlertController

在Xcode中查看UIAlertView声明

// UIAlertView is deprecated. Use UIAlertController with a preferredStyle of   UIAlertControllerStyleAlert instead
class UIAlertView : UIView {
Run Code Online (Sandbox Code Playgroud)

仅限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)
Run Code Online (Sandbox Code Playgroud)

更新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)
Run Code Online (Sandbox Code Playgroud)