Swift 警报弹出窗口出现在模拟器 iphone 4s(8.1) 中,而不是 iphone 4s (7.1)

Swift Alert popup is appearing in simulator iphone4s(8.1), not iphone4s (7.1)

我编写了代码来在单击按钮时显示一个简单的警报弹出窗口。在模拟器 iPhone 4s (8.1) 中尝试应用程序时,它按预期工作,但在模拟器 iPhone 4s (7.1) 中尝试时,应用程序不断崩溃。

这里是代码:

@IBAction func buttonPressed(发件人:UIButton){

    let controller = UIAlertController(title: "This is a title", message: "Hello, my friend", preferredStyle: UIAlertControllerStyle.Alert)
    let cancelAction = UIAlertAction(title: "Phew!", style: .Cancel, handler: nil)
    controller.addAction(cancelAction)
    self.presentViewController(controller, animated: true, completion: nil)
}

错误信息如下:

第一行代码(创建 "controller" 常量的代码)以绿色突出显示并显示消息 "Thread 1: EXC_BAD_ACCESS(Code=1,address=0x10)"

如有任何帮助,我将不胜感激

UIAlertController 适用于 iOS >= 8.0

iOS < 8.0

你必须使用 UIAlertView

UIAlertController 仅在 iOS 8.0 中可用,不幸的是,这是文档,它在右侧说明了这一点:https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIAlertController_class/#//apple_ref/doc/uid/TP40014538-CH1-SW2

I believe this replaced the now deprecated UIAlertView which can be found here in Apple Documentation: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIAlertView_Class/index.html#//apple_ref/occ/cl/UIAlertView

Swift 不喜欢旧的但考虑 "if" 子句并使用应用程序为各自的 iOS 系统创建 UIAlertView 和 UIAlertController。

感谢 Dom Bryan 推荐的链接,我管理了以下解决方案:

@IBAction func buttonPressed(发件人:UIButton){

    if NSClassFromString("UIAlertController") == nil{
        let alert = UIAlertView(title: "This is a title", message: "I am an iOS7 alert", delegate: self, cancelButtonTitle: "Phew!")
        alert.show()
    }else{
        let controller = UIAlertController(title: "This is a title", message: "Hello, my friend", preferredStyle: .Alert)
        let cancelAction = UIAlertAction(title: "Phew!", style: .Cancel, handler: nil)
        controller.addAction(cancelAction)
        self.presentViewController(controller, animated: true, completion: nil)
    }
}

它在 iOS7 和 iOS8 设备上运行良好