UIAlertController的使用
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let btn = UIButton(type: .contactAdd)
btn.center = self.view.center
btn.addTarget(self, action: #selector(btnClick), for: .touchUpInside)
self.view.addSubview(btn)
// 在该方法中present不出来alertController, 因为此时view还没加载完毕
// self.setupAlertController()
}
func btnClick() {
self.setupOtherAlertController()
}
func setupAlertController() {
let alertController = UIAlertController(title: "提示", message: "您确定要离开吗", preferredStyle: .alert)
let okAlertAction = UIAlertAction(title: "确定", style: .default) { (ACTION) in
print("确定")
}
let cancelAlertAction = UIAlertAction(title: "取消", style: .cancel) { (ACTION) in
print("取消")
}
alertController.addAction(okAlertAction)
alertController.addAction(cancelAlertAction)
self.present(alertController, animated: true, completion: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// 在该方法中present可以出来alertController, 因为此时view已经加载完毕,view已经显示出来
// self.setupAlertController()
// self.setupOtherAlertController()
}
func setupOtherAlertController() {
let alertController = UIAlertController(title: "登录", message: "请输入用户名和密码", preferredStyle: .alert)
alertController.addTextField { (textField: UITextField) in
textField.placeholder = "用户名:"
}
alertController.addTextField { (textField: UITextField) in
print("密码:")
}
let okAlertAction = UIAlertAction(title: "确定", style: .default) { (ACTION) in
// let login = (alertController.textFields?.first)! as UITextField
let loginText = alertController.textFields?.first?.text
// let password = (alertController.textFields?.last)! as UITextField
let passwordText = alertController.textFields?.last?.text
print("用户名:\(loginText) 密码:\(passwordText)")
}
let cancelAlertAction = UIAlertAction(title: "取消", style: .cancel) { (ACTION) in
print("取消")
}
alertController.addAction(okAlertAction)
alertController.addAction(cancelAlertAction)
self.present(alertController, animated: true, completion: nil)
}
}
网友评论