Swift_IOSz之提示框(UIAlertController)《一》

import UIKit

class ViewController: UIViewController ,UIActionSheetDelegate{
    @IBAction func btn1(_ sender: UIButton) {
        label1.text="文本显示"
        let alertController = UIAlertController(title: "修改文本", message: nil, preferredStyle: UIAlertControllerStyle.alert)
        alertController.addTextField(configurationHandler: { (textField: UITextField!) -> Void in
            textField.placeholder = "请输入内容"
            // 添加监听代码,监听文本框变化时要做的操作
            NotificationCenter.default.addObserver(self, selector: #selector(self.alertTextFieldDidChange), name: NSNotification.Name.UITextFieldTextDidChange, object: textField)
        })
        let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: nil)
       
        let okAction = UIAlertAction(title: "确认", style: UIAlertActionStyle.default , handler: { (action: UIAlertAction!) -> Void in
            let login = (alertController.textFields?.first)! as UITextField
            let str = login.text
            self.label1.text=str
            NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UITextFieldTextDidChange, object: nil)
        })
        okAction.isEnabled = false
        alertController.addAction(cancelAction)
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    /// 监听文字改变
    @objc func alertTextFieldDidChange(){
        let alertController = self.presentedViewController as! UIAlertController?
        if (alertController != nil) {
            let login = (alertController!.textFields?.first)! as UITextField
            let okAction = alertController!.actions.last! as UIAlertAction
            if (!(login.text?.isEmpty)!) {
                okAction.isEnabled = true
            } else {
                okAction.isEnabled = false
            }
        }
    }
    
    @IBOutlet weak var label1: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    @IBOutlet weak var hello: UILabel!
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

 效果图

猜你喜欢

转载自www.cnblogs.com/loaderman/p/10293571.html