swift中的警报错误

时间:2014-06-08 17:20:56

标签: 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()
}

Xcode在编译时不会显示错误。

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

(lldb)
thread 1 EXC_BAD_ACCESS(code 1 address=0x20)

1 个答案:

答案 0 :(得分:41)

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

let alert = UIAlertView()
alert.title = "Hey"
alert.message = "This is  one Alert"
alert.addButtonWithTitle("Working!!")
alert.show()

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

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

Xcode中的UIAlertView声明视图

// UIAlertView is deprecated. Use UIAlertController with a preferredStyle of   UIAlertControllerStyleAlert instead
class UIAlertView : UIView {

仅限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)

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)