How to limit characters in UITextField

cocoa-touch, ios, iphone, objective-c, uitextfield

Solution

o limit the text field use below code.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
     NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];    
        return !([newString length] > 3);

}

Problem

I have a `UITextField` with the following restrictions - characters can only be numbers, as in the method below. I want to also limit the number of max characters to 3 digits. How can I modify my method to do that? ``` - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSCharacterSet *aCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"]; for (int i = 0; i < [string length]; i++) { unichar aCharacter = [string characterAtIndex:i]; if ([aCharacterSet characterIsMember:aCharacter]) { return YES; } } NSUInteger newLength = self.textField.text.length + string.length - range.length; return (newLength > 3) ? NO : YES; } ```

Original source

Related problems