Is there any way to set the maximum length on a UITextField?
Something like the MAXLENGTH attribute in HTML input fields.
If you have a UITextField or UITextView and want to stop users typing in more than a certain number of letters, you need to set yourself as the delegate for the control then implement either shouldChangeCharactersIn (for text fields) or shouldChangeTextIn (for text views).
Create textLimit method This is the first step in limiting the characters for a text field or a text view. We need to create a method that will limit the the number of characters based on the current character count and the additional/new text that will get appended to the current value of the text field or text view.
The maxlength attribute specifies the maximum number of characters that can be entered. By default, the maximum is 524,288 characters.
Swift – String Length/Count To get the length of a String in Swift, use count property of the string. count property is an integer value representing the number of characters in this string.
This works correctly with backspace and copy & paste:
#define MAXLENGTH 10 - (BOOL)textField:(UITextField *) textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSUInteger oldLength = [textField.text length]; NSUInteger replacementLength = [string length]; NSUInteger rangeLength = range.length; NSUInteger newLength = oldLength - rangeLength + replacementLength; BOOL returnKey = [string rangeOfString: @"\n"].location != NSNotFound; return newLength <= MAXLENGTH || returnKey; }
UPDATE: Updated to accept the return key even when at MAXLENGTH. Thanks Mr Rogers!
UPDATE
I cannot delete this answer because it is the accepted one, but it was not correct. Here is the correct code, copied from TomA below:
#define MAXLENGTH 10 - (BOOL)textField:(UITextField *) textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSUInteger oldLength = [textField.text length]; NSUInteger replacementLength = [string length]; NSUInteger rangeLength = range.length; NSUInteger newLength = oldLength - rangeLength + replacementLength; BOOL returnKey = [string rangeOfString: @"\n"].location != NSNotFound; return newLength <= MAXLENGTH || returnKey; }
ORIGINAL
I think you mean UITextField. If yes, then there is a simple way.
textField:shouldChangeCharactersInRange:replacementString:
method.That method gets called on every character tap or previous character replacement. in this method, you can do something like this:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if ([textField.text length] > MAXLENGTH) { textField.text = [textField.text substringToIndex:MAXLENGTH-1]; return NO; } return YES; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With