如何在iOS中限制UITextField中的数字?

时间:2015-03-19 04:40:26

标签: ios uitextfield

我在UITextField中创建了US Mobile格式,它允许US Format手机号码成功(1-222-304-9876),但它也允许这种类型的号码(1-234-56)。如何限制数字,我的UITextField只允许14个字符。请检查我的代码...如何控制那个。

- (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]) {
            if (alertCheck == NO) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Alphbets and Special characters not allowed" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];

                alertCheck = YES;
            }
            return NO;
        }

    }
}

NSString *acceptedcharacters = @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789-/";
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:acceptedcharacters] invertedSet];


if ([string isEqualToString:@"0"] && range.location == 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];
 return (([string isEqualToString:filtered]) && (newLength <= 14));
}

0 个答案:

没有答案