Created
July 10, 2017 01:29
-
-
Save bhrott/405ae9b6cd977d62fd359c6ba6fa1694 to your computer and use it in GitHub Desktop.
Apply max length to UITextField in swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
thanks men
Thank you very much
Hi, if the maximum length I want to give it only to 2 textfields out of 5?
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
awesome! thanks!