swift中UIAlertController的使用

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)
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容