In this example, We have shared set the maximum character length of a uitextfield in swift While the UITextField class has no max length property, it’s relatively simple to get this functionality by setting the text field’s delegate and implementing the following delegate method:
Objective-C
1 2 3 4 5 6 7 8 9 10 |
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { // Prevent crashing undo bug – see note below. if(range.length + range.location > textField.text.length) { return NO; } NSUInteger newLength = [textField.text length] + [string length] - range.length; return newLength <= 25; } |
Swift 4
1 2 3 4 5 6 7 8 9 |
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let currentCharacterCount = textField.text?.count ?? 0 if range.length + range.location > currentCharacterCount { return false } let newLength = currentCharacterCount + string.count - range.length return newLength <= 25 } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.