Upvote:2

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    return textField.text!.count + string.count < 5
}

More Answer related to the Same Query

Upvote:1

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    return string.isEmpty || (textField.text?.count ?? 0) < 4
}

Upvote:0

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    let newLength = textField.text.length + (string.length - range.length)

    if newLength <= maxLength {
       return true
    } else {
       return false 
    }
}

More Answer related to the Same Query

Upvote:0

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?.count ?? 0
  let lengthToAdd = string.count
  let lengthToReplace = range.length

  let newLength = startingLength + lengthToAdd - lengthToReplace

  return newLength <= characterCountLimit
}

Credit Goes to: stackoverflow.com

Related question with same questions but different answers