Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 567
Alexander Tkachenko Avatar asked Jan 19 '11 17:01

Alexander Tkachenko


2 Answers

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;
} 
like image 69
WrightsCS Avatar answered Oct 27 '22 12:10

WrightsCS


I prefer the following solution that actually prevents any any input except from numbers and backspace. Backspace for some reason is represented by an empty string and could not be used unless empty string returns YES. I also popup an alert view when the user enters a character other that numbers.

- (BOOL)textField:(UITextField *)theTextField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{
    if (string.length == 0) {
        return YES;
    }
    NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    for (int i = 0; i < [string length]; i++) {
        unichar c = [string characterAtIndex:i];
        if ([myCharSet characterIsMember:c]) {
            return YES;
        }
    }
    UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Invalid Input" message:@"Only numbers are allowed for participant number." delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
    [av show];
    return NO;
}
like image 36
zirinisp Avatar answered Oct 27 '22 13:10

zirinisp