Set the maximum numbers of characters of the UITextField (Swift 4.x-5.x)

Set the maximum numbers of characters of the UITextField (Swift 4.x)
Set the maximum numbers of characters of the UITextField (Swift 4.x)

It happens that you need to protect the user from entering too much characters in the UITextField. First of all, the amount of data that it will enter doesn’t exist in the world (for example, phone number of 100 characters). Secondly, it will destroy the design of your application.

Below is a specific example for Swift 4.x-5.0 where the user cannot enter more than five characters. I use it in my application.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
  let maxLength = 5
  let currentString: NSString = textField.text! as NSString
  let newString: NSString =
    currentString.replacingCharacters(in: range, with: string) as NSString
  return newString.length <= maxLength
}