I would like to count the character when user keep typing in UITextField with swift.
Image of Field and Label:
Here's how you could do it in Swift 3/4.
First, make sure you've got your textField's delegate set in viewDidLoad
.
yourTextField.delegate = self
Then, implement shouldChangeCharactersIn
:
extension YourViewController: UITextFieldDelegate {
func textField(_ textFieldToChange: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// limit to 4 characters
let characterCountLimit = 4
// We need to figure out how many characters would be in the string after the change happens
let startingLength = textFieldToChange.text?.characters.count ?? 0
let lengthToAdd = string.characters.count
let lengthToReplace = range.length
let newLength = startingLength + lengthToAdd - lengthToReplace
return newLength <= characterCountLimit
}
}
Additional details here