美国格式的ios手机号码?

时间:2015-03-16 06:40:44

标签: ios

我想要显示" 1(xxx) - (xxx) - (xxx)"在UITextfield中,只输入10位数字。

  • 它的有效1到9个数字。
  • 它只开始1.
  • 如果输入0,则不会被拍摄。

我如何实现这一目标?

1 个答案:

答案 0 :(得分:2)

我在其中一个项目中完成了我们的电话号码验证。希望这对你有所帮助。

-(void)textFieldDidBeginEditing:(UITextField *)textField {
 [textField performSelector:@selector(shouldChangeTextInRange:replacementText:)];
}

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

    NSString *acceptedcharacters = @"0123456789-/";
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:acceptedcharacters] invertedSet];
    const char * _char = [string cStringUsingEncoding:NSUTF8StringEncoding];
    int isBackSpace = strcmp(_char, "\b");
    if (isBackSpace == -8) {
        NSLog(@"deleted");
    }
    else {
        if (textField.text.length == 1) {

            textField.text = [NSString stringWithFormat:@"%@-",text];
            return YES;
        }
        if (textField.text.length == 5) {

            textField.text = [NSString stringWithFormat:@"%@-",text];
            return YES;
        }
        if (textField.text.length == 9) {

            textField.text = [NSString stringWithFormat:@"%@-",text];
            return YES;
        }
    }
    //   if (textField == self.phoneNumber_txtField) {
    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    return (newLength > 14) ? NO : YES;

    //  }

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

    return [string isEqualToString:filtered];
 }