我一直在努力创建一个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)
}
适用于13.0以上版本
使用SceneDelegate
适用于所有类型的课程
static func showWindowAlert(alertMessage: String, inVC:UIViewController) {
DispatchQueue.main.async(execute: {
guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
let sceneDelegate = windowScene.delegate as? SceneDelegate
else {
return
}
sceneDelegate.window?.rootViewController = inVC
sceneDelegate.window?.windowLevel = UIWindow.Level.alert + 1
let alert2 = UIAlertController(title: App_Name, message: alertMessage, preferredStyle: .alert)
let defaultAction2 = UIAlertAction(title: "OK", style: .default, handler: { action in
})
alert2.addAction(defaultAction2)
sceneDelegate.window?.makeKeyAndVisible()
sceneDelegate.window?.rootViewController?.present(alert2, animated: true, completion: nil)
})
}
我找到了这个,
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...)
}
也许有人能解释一下。
下面是Swift中AlertView的一个非常简单的函数:
class func globalAlertYesNo(msg: String) {
let alertView = UNAlertView(title: "Title", message: msg)
alertView.messageAlignment = NSTextAlignment.Center
alertView.buttonAlignment = UNButtonAlignment.Horizontal
alertView.addButton("Yes", action: {
print("Yes action")
})
alertView.addButton("No", action: {
print("No action")
})
alertView.show()
}
在使用此函数时,必须将message作为字符串传递。
使用此代码显示alertview
let alertController = UIAlertController(title: "Hello Coders", message: "your alert message", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "Close Alert", style: .Default, handler: nil)
alertController.addAction(defaultAction)
presentViewController(alertController, animated: true, completion: nil)
Swift显示警报使用UIAlertController