swift4--动态获取UIUITextField内的字符串

//
//  ViewController.swift
//  testTextFilde
//


import UIKit

class ViewController: UIViewController , UITextFieldDelegate {
    @IBOutlet weak var textField: UITextField!
    
    @IBOutlet weak var testlable: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        textField.delegate = self
    }

    //该方法用来检测UITextField内容的改变,需要添加UITextFieldDelegate
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        //注意下面这句代码,不这样做得到的字符串会是你上一次输入的,这是String和NSString的截取机制导致的
        let fullStr = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        self.testlable.text = fullStr
        return true
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}



猜你喜欢

转载自blog.csdn.net/weixin_41735943/article/details/82714241