我正在尝试在新的Xcode更新8.3.2中做简单警报我在呈现警报对话框时遇到问题:
@IBAction func testButonAlert()
{
let alertAction = UIAlertAction( title : "Hi TEst" ,
style : UIAlertActionStyle.destructive,
handler : { ( UIAlertActionStyle) -> Void in print("") })
self.present(alertAction , animated: false, completion: nil)
}
错误:
无法将'UIAlertAction'类型的值转换为预期的参数类型'UIViewController'
你将呈现action
这是不可能的(并导致错误)。
您需要父级UIAlertController
来附加操作,例如:
@IBAction func testButonAlert()
{
let alertController = UIAlertController(title: "Hi TEst", message: "Choose the action", preferredStyle: .alert)
let alertAction = UIAlertAction( title : "Delete Me" ,
style : .destructive) { action in
print("action triggered")
}
alertController.addAction(alertAction)
self.present(alertController, animated: false, completion: nil)
}
你应该使用UIAlertController。
let alertVC = UIAlertController(title: "title", message: "message", preferredStyle: .alert)
alertVC.addAction(UIAlertAction(title: "Close", style: .default, handler: nil))
self.present(alertVC, animated: true, completion: nil)
您只需使用UIAlertController
创建警报:
let yourAlert = UIAlertController(title: "Alert header", message: "Alert message text.", preferredStyle: UIAlertControllerStyle.alert)
yourAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (handler) in
//You can also add codes while pressed this button
}))
self.present(yourAlert, animated: true, completion: nil)
对于Swift 4.0
class func showAlert(_ title: String, message: String, viewController: UIViewController,
okHandler: @escaping ((_: UIAlertAction) -> Void),
cancelHandler: @escaping ((_: UIAlertAction) -> Void)) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default, handler: okHandler)
alertController.addAction(OKAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: cancelHandler)
alertController.addAction(cancelAction)
viewController.present(alertController, animated: true, completion: nil)
}