ios - 我将如何在 Swift 中创建一个 UIAlertView?

标签 ios swift cocoa-touch uialertview uialertcontroller

我一直在努力在 Swift 中创建一个 UIAlertView,但由于某些原因我无法正确声明,因为我收到此错误:

Could not find an overload for 'init' that accepts the supplied arguments

我是这样写的:

let button2Alert: UIAlertView = UIAlertView(title: "Title", message: "message",
                     delegate: self, cancelButtonTitle: "OK", otherButtonTitles: nil)

然后调用它我正在使用:

button2Alert.show()

截至目前它正在崩溃,我似乎无法获得正确的语法。

最佳答案

来自 UIAlertView 类:

// UIAlertView is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead

在 iOS 8 上,您可以这样做:

let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)

现在 UIAlertController 是一个单独的类,用于创建 iOS 8 上的 UIAlertViewUIActionSheet 并与之交互。

编辑:处理操作:

alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { action in
    switch action.style{
    case .Default:
        print("default")
        
    case .Cancel:
        print("cancel")
        
    case .Destructive:
        print("destructive")
    }
}}))

为 Swift 3 编辑:

let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)

为 Swift 4.x 编辑:

let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
    switch action.style{
        case .default:
        print("default")
        
        case .cancel:
        print("cancel")
        
        case .destructive:
        print("destructive")
        
    }
}))
self.present(alert, animated: true, completion: nil)

关于ios - 我将如何在 Swift 中创建一个 UIAlertView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24022479/

相关文章:

ios - MPSCNNConvolutionDescriptor neuronFilter 已弃用

ios - 使用Facebook SDK 4.20 iOS从Facebook获取所有 friend 列表

ios - 在NSString中,长度是属性还是函数?

ios - 来自字符串的 UUID 始终为零

iphone - 以编程方式将显示 image1 的 UIImageView 更改为 image2

cocoa-touch - 平均作为获取的属性?

ios - iOS swift 中推送通知的文本对齐

ios - 如何在 Parse.com 中向我的类(class)添加另一列? ( swift )

json - 我的 JSON 解析不起作用

objective-c - 反转 UILabel.text 值