Farhad Nežad Farhad Nežad - 7 months ago 30
Swift Question

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

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

Image of Field and Label:

enter image description here

I have already placed UITextField and UILabel, just haven't found any information on Stack overflow, also if you can do one in UITextView I also appreciate it.

Answer

To use the function below you need to implement the UITextFieldDelegate protocol of the text field you want to count, this function gets called everytime the UITextField change value:

Your class declaration should look something like this

class ViewController: UIViewController, UITextFieldDelegate

You should have an @IBOutlet similar to this

@IBOutlet var txtValue: UITextField

In viewDidLoad you set the delegate method 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
    //change the value of the label
    mylabel.text =  String(newLength)
    //you can save this value to a global var
    //myCounter = newLength
    //return true to allow the change, if you want to limit the number of characters in the text field use something like
    return newLength <= 25 // To just allow up to 25 characters
    return true
}

Remember this function is called to all UITextField so if you have many UITextField you will need to add a logic to know witch one is calling this function, just add a different tag to each UITextField and use a switch statement to find with UITextField call the function