如何在UITextField中允许零?

时间:2015-03-18 09:10:55

标签: ios uitextfield

它允许在textfield中只有1到9个数字。 UITextfield中的索引位置0不允许归零。但我的代码在UITextfield中不允许为零。检查此代码。一旦' S

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

你的代码在这里返回NO:

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

试试这个:

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