How to do a live UITextField count while typing (Swift)?

后端 未结 10 1231
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 13:37

I would like to count the character when user keep typing in UITextField with swift.

Image of Field and Label:

10条回答
  •  执念已碎
    2020-12-05 14:16

    To use the function below you need to implement the UITextFieldDelegate protocol on the text field you want to count. This gets called every time the UITextFields text changes:

    Your class declaration should look something like this

    class ViewController: UIViewController, UITextFieldDelegate
    

    You should have an @IBOutlet similar to this

    @IBOutlet var txtValue: UITextField
    

    Set the UITextField s delegate to self.

    override func viewDidLoad() {
        super.viewDidLoad()
        txtValue.delegate = self                
    }
    
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        let newLength = count(textField.text.utf16) + count(string.utf16) - range.length
    
        mylabel.text =  String(newLength) // Set value of the label
        // myCounter = newLength // Optional: Save this value
        // return newLength <= 25 // Optional: Set limits on input. 
        return true
    }
    

    Note that this function is called on all UITextFields so if you have several UITextFields you will need to add a logic to know witch one is calling this function.

提交回复
热议问题