我一直在努力在 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 上的 UIAlertView
和 UIActionSheet
并与之交互。
编辑:处理操作:
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/