我一直在努力创建一个UIAlertView在Swift,但由于某种原因,我不能得到正确的声明,因为我得到这个错误:
无法找到一个超载的'init'接受提供的
参数
我是这样写的:
let button2Alert: UIAlertView = UIAlertView(title: "Title", message: "message",
delegate: self, cancelButtonTitle: "OK", otherButtonTitles: nil)
然后我使用:
button2Alert.show()
到目前为止,它正在崩溃,我只是不能得到正确的语法。
let alertController = UIAlertController(title: "Select Photo", message: "Select atleast one photo", preferredStyle: .alert)
let action1 = UIAlertAction(title: "From Photo", style: .default) { (action) in
print("Default is pressed.....")
}
let action2 = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
print("Cancel is pressed......")
}
let action3 = UIAlertAction(title: "Click new", style: .default) { (action) in
print("Destructive is pressed....")
}
alertController.addAction(action1)
alertController.addAction(action2)
alertController.addAction(action3)
self.present(alertController, animated: true, completion: nil)
}
对于SWIFT4,我认为扩展UIViewController并创建一个可重用的确认控件是最优雅的方式。
你可以像下面这样扩展UIViewController:
extension UIViewController {
func AskConfirmation (title:String, message:String, completion:@escaping (_ result:Bool) -> Void) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
self.present(alert, animated: true, completion: nil)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { action in
completion(true)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { action in
completion(false)
}))
}
}
那么你可以随时使用它:
AskConfirmation(title: "YOUR MESSAGE TITLE", message: "YOUR MESSAGE") { (result) in
if result { //User has clicked on Ok
} else { //User has clicked on Cancel
}
}
SWIFT 4:简单地为UIViewController创建一个扩展,如下所示:
extension UIViewController {
func showSuccessAlert(withTitle title: String, andMessage message:String) {
let alert = UIAlertController(title: title, message: message,
preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK".localized, style:
UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
现在在你的ViewController中,直接调用上面的函数,就好像它们是由UIViewController提供的一样。
yourViewController.showSuccessAlert(withTitle:
"YourTitle", andMessage: "YourCustomTitle")
我得到了以下UIAlertView初始化代码编译没有错误(我认为最后,变量部分可能是棘手的)。但我必须确保类的自我(我传递的委托)采用UIAlertViewDelegate协议编译错误消失:
let alertView = UIAlertView(
title: "My Title",
message: "My Message",
delegate: self,
cancelButtonTitle: "Cancel",
otherButtonTitles: "OK"
)
顺便说一下,这是我得到的错误(作为Xcode 6.4):
无法为类型“UIAlertView”找到接受参数的初始化式
类型为'的参数列表(标题:字符串,消息:字符串,委托:
MyViewController, cancelButtonTitle: String, otherbuttontitle:
字符串)”
正如其他人提到的,如果你的目标是iOS 8.x+,你应该迁移到UIAlertController。要支持iOS 7,请使用上面的代码(Swift不支持iOS 6)。