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

醉酒当歌 提交于 2019-12-03 09:55:51

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

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