Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bhrott/405ae9b6cd977d62fd359c6ba6fa1694 to your computer and use it in GitHub Desktop.
Save bhrott/405ae9b6cd977d62fd359c6ba6fa1694 to your computer and use it in GitHub Desktop.
Apply max length to UITextField in swift
extension MyViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else { return true }
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= 30 // replace 30 for your max length value
}
}
@rgkobashi
Copy link

awesome! thanks!

@victorJaramillo
Copy link

thanks men

Copy link

ghost commented Feb 21, 2018

Thank you very much

@0xa0ax0
Copy link

0xa0ax0 commented May 27, 2020

Hi, if the maximum length I want to give it only to 2 textfields out of 5?

@elenamene
Copy link

elenamene commented Jun 2, 2020

Hi, if the maximum length I want to give it only to 2 textfields out of 5?

you need to check which textField is in the guard statement:

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard textField == textFieldWithMaxLength, let text = textField.text else { return true }
        let newLength = text.characters.count + string.characters.count - range.length
        return newLength <= 30 // replace 30 for your max length value
   }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment