Alexander Tkachenko Alexander Tkachenko - 1 month ago 8
Objective-C Question

How to disable letter characters in UITextField?

In my application i need to allow users input only numbers.
How can i allow UITextField to receive only numbers from user?

Answer

The characters in this examples are allowed, so if you dont want the user to use a character, exclude it from myCharSet.

- (BOOL)textField:(UITextField *)theTextField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{
    NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    for (int i = 0; i < [string length]; i++) {
        unichar c = [string characterAtIndex:i];
        if (![myCharSet characterIsMember:c]) {
            return NO;
        }
    }

    return YES;
}