swift5学习之旅-----UIAlertController
三种类型的Alert
- 整体代码
Github还没上传,先用着Dropbox(可能要翻墙),看完有收获的感谢点个赞👍,如果翻不了墙要代码可以私聊我
https://www.dropbox.com/sh/vp94ctk73frp97t/AABuyZ47DpyjALWjcNjRk480a?dl=0
- UIAlertController基本使用方法
let alertController = UIAlertController(title: "登录界面", message: "请输入用户名和密码", preferredStyle: .alert)
alertController.addTextField { (textField) in
textField.placeholder = "请输入用户名"
}
alertController.addTextField { (textField) in
textField.placeholder = "密码"
textField.isSecureTextEntry = true
}
let okAction = UIAlertAction(title: "确认", style: .default) { (action) in
let login = self.alertController.textFields!.first!
let password = self.alertController.textFields!.last!
print("用户名:\(String(describing: login.text))密码:\(String(describing: password.text))")
}
let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
let unknow = UIAlertAction(title: "中间且红色", style: .destructive) { (UIAlertAction) in
print("红色")
}
alertController.addAction(cancelAction)
alertController.addAction(okAction)
alertController.addAction(unknow)
- Extension UIAlertController
extension UIAlertController {
//在指定视图控制器上弹出普通消息提示框
static func showAlert(message: String, in viewController: UIViewController) {
let alert = UIAlertController(title: "Extension Alert", message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "确定", style: .cancel))
viewController.present(alert, animated: true)
}
//在根视图控制器上弹出普通消息提示框
static func showAlert(message: String) {
if let vc = UIApplication.shared.windows.filter({$0.isKeyWindow}).first?.rootViewController {
showAlert(message: message, in: vc)
}
}
//在指定视图控制器上弹出确认框
static func showConfirm(message: String, in viewController: UIViewController,
confirm: ((UIAlertAction)->Void)?) {
let alert = UIAlertController(title: "Extension Alert", message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "取消", style: .cancel))
alert.addAction(UIAlertAction(title: "确定", style: .default, handler: confirm))
viewController.present(alert, animated: true)
}
//在根视图控制器上弹出确认框
static func showConfirm(message: String, confirm: ((UIAlertAction)->Void)?) {
if let vc = UIApplication.shared.windows.filter({$0.isKeyWindow}).first?.rootViewController {
showConfirm(message: message, in: vc, confirm: confirm)
}
}
}