如何在 UITextField 中允许零?

How to allow zero's in UITextField?

它只允许在文本字段中输入 1 到 9 个数字。 UITextfield 中的索引位置 0 不允许零。但我的代码不允许在 UITextfield 中为零。检查此代码。曾经的

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string  {
    NSString *text = mobileNo.text;

    if(textField==mobileNo) {
        NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
        for (int i = 0; i < [string length]; i++) {
            unichar c = [string characterAtIndex:i];
            if (![myCharSet characterIsMember:c]) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Alphbets and Special characters not allowed" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
                return NO;
            }
        }
    }

    NSString *acceptedcharacters = @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-/";



    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:acceptedcharacters] invertedSet];

    if ([string hasPrefix:@"0"]) {
        return NO;
    }

    const char * _char = [string cStringUsingEncoding:NSUTF8StringEncoding];
    int isBackSpace = strcmp(_char, "\b");
    if (isBackSpace == -8) {
        NSLog(@"deleted");
    } else {
        if (mobileNo.text.length == 1) {
            mobileNo.text = [NSString stringWithFormat:@"%@-",text];
            return YES;
        }
        if (mobileNo.text.length == 5) {
            mobileNo.text = [NSString stringWithFormat:@"%@-",text];
            return YES;
        }
        if (mobileNo.text.length == 9) {
            mobileNo.text = [NSString stringWithFormat:@"%@-",text];
            return YES;
        }
    }
//  if (textField == self.phoneNumber_txtField) {
        NSUInteger newLength = [mobileNo.text length] + [string length] - range.length;
        return (newLength > 14) ? NO : YES;
//  }

    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

    return [string isEqualToString:filtered];
}
#define ACCEPTABLE_CHARECTERS @"123456789."

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string  {

    if (textField==textFieldAmount)
    {
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARECTERS] invertedSet];

        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

        return [string isEqualToString:filtered];
    }
    return YES;
}

您在此处编码 returns 否:

if ([string hasPrefix:@"0"]) {
    return NO;
}

试试这个:

if ([string isEqualToString:@"0"] && range.location == 0) {
    return NO;
}