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

南笙酒味 提交于 2020-01-01 04:01:23

问题


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?


回答1:


The following code will allow you to only input numbers as well as limit the amount of characters that can be used.

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{
    /*  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;
        }
    }

    /*  limit the users input to only 9 characters  */
    NSUInteger newLength = [customTextField.text length] + [string length] - range.length;
    return (newLength > 9) ? NO : YES;
}



回答2:


-(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;
}



回答3:


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;


来源:https://stackoverflow.com/questions/6809609/objective-c-numbers-only-text-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!