Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: Numbers only text field? [duplicate]

Tags:

Possible Duplicate:
Iphone UITextField only integer

I want to place a text field that only accepts numbers (0-9, doesn't even need decimals), but even using the "Number Pad" entry option I still get a keyboard with various symbols on it. Is there a better control for this, is there a better control for what I'm doing, or do I just have to validate input manually?

like image 459
RCIX Avatar asked Jul 24 '11 20:07

RCIX


2 Answers

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
/* for backspace */    
    if([string length]==0){
       return YES;
    }

/*  limit to only numeric characters  */

    NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    for (int i = 0; i < [string length]; i++) {
       unichar c = [string characterAtIndex:i];
       if ([myCharSet characterIsMember:c]) {
          return YES;
      }
    }

return NO;
}
like image 191
Rakesh Bhatt Avatar answered Oct 07 '22 17:10

Rakesh Bhatt


The code is somehow incorrect, should be

/*  limit to only numeric characters  */
NSCharacterSet* numberCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
for (int i = 0; i < [string length]; ++i)
{
    unichar c = [string characterAtIndex:i];
    if (![numberCharSet characterIsMember:c])
    {
        return NO;
    }
}

return YES;
like image 26
Zheng Te Avatar answered Oct 07 '22 17:10

Zheng Te