美国格式的手机号码在ios



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

  • 它是有效的 1 到 9 个数字。
  • 它只开始 1。
  • 如果输入 0,则不会采用。

我如何实现这一点?

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

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