I'm looking for a way to minimize characters in textfield. Since the textfield is for username input, I want to make users input 4 characters minimum to 30 characters maximum. First, I made textfield shouldChangeCharactersIn
to set maximum characters in textfield. The code looks good but the problem when I want to make users if the username text field is less than 4 characters the app gives them error or to return false.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let currentString = usernameTextField.text!.characters.count ?? 0
if (range.length + range.location > currentString) {
return false
}
let newLength = currentString + string.characters.count - range.length
return newLength <= 30
}
Any help ?