我一直在努力创建一个UIAlertView在Swift,但由于某种原因,我不能得到正确的声明,因为我得到这个错误:
无法找到一个超载的'init'接受提供的
参数
我是这样写的:
let button2Alert: UIAlertView = UIAlertView(title: "Title", message: "message",
delegate: self, cancelButtonTitle: "OK", otherButtonTitles: nil)
然后我使用:
button2Alert.show()
到目前为止,它正在崩溃,我只是不能得到正确的语法。
我还有一招。假设您有5个类,其中要应用注销警报。尝试使用swift类扩展。
文件-新建- Swift类-命名。
增加如下内容:
public extension UIViewController
{
func makeLogOutAlert()
{
var refreshAlert = UIAlertController(title: "Log Out", message: "Are You Sure to Log Out ? ", preferredStyle: UIAlertControllerStyle.Alert)
refreshAlert.addAction(UIAlertAction(title: "Confirm", style: .Default, handler: { (action: UIAlertAction!) in
self.navigationController?.popToRootViewControllerAnimated(true)
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction!) in
refreshAlert .dismissViewControllerAnimated(true, completion: nil)
}))
presentViewController(refreshAlert, animated: true, completion: nil)
}
}
实现使用:self.makeLogOutAlert()。希望能有所帮助。
我找到了这个,
var alertView = UIAlertView();
alertView.addButtonWithTitle("Ok");
alertView.title = "title";
alertView.message = "message";
alertView.show();
虽然不是很好,但它有效:)
更新:
但我在头文件上发现为:
extension UIAlertView {
convenience init(title: String, message: String, delegate: UIAlertViewDelegate?, cancelButtonTitle: String?, otherButtonTitles firstButtonTitle: String, _ moreButtonTitles: String...)
}
也许有人能解释一下。
斯威夫特3
下面是一个简单的例子,如何用Swift 3一个按钮创建一个简单的警报。
let alert = UIAlertController(title: "Title",
message: "Message",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default))
present(alert, animated: true)
在上面的例子中,动作的句柄回调被省略了,因为带有一个按钮的警报视图的默认行为是在单击按钮时消失。
下面是如何创建另一个动作,可以用"alert. addaction (action)"添加到警报中。不同的样式是.default, .destructive和.cancel。
let action = UIAlertAction(title: "Ok", style: .default) { action in
// Handle when button is clicked
}
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")