0

在 iPhone 联系人 tableview 中有一个名为“电话”的单元格,当用户编辑此手机号码时,会变成这样:(251) 575-3621。我怎样才能制作这种细胞类型?

谢谢..

4

1 回答 1

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


NSUInteger currentLength = textField.text.length;


NSCharacterSet *numbers = [NSCharacterSet decimalDigitCharacterSet];


if (range.length == 1) {
    return YES;
}


if ([numbers characterIsMember:[string characterAtIndex:0]]) {


    if ( currentLength == 3 ) 
    {

        if (range.length != 1) 
        {

            NSString *firstThreeDigits = [textField.text substringWithRange:NSMakeRange(0, 3)];

            NSString *updatedText;

            if ([string isEqualToString:@"-"]) 
            {
                updatedText = [NSString stringWithFormat:@"%@",firstThreeDigits];
            }

            else 
            {
                updatedText = [NSString stringWithFormat:@"%@-",firstThreeDigits];
            }

            [textField setText:updatedText];
        }           
    }

    else if ( currentLength > 3 && currentLength < 8 ) 
    {

        if ( range.length != 1 ) 
        {

            NSString *firstThree = [textField.text substringWithRange:NSMakeRange(0, 3)];
            NSString *dash = [textField.text substringWithRange:NSMakeRange(3, 1)];

            NSUInteger newLenght = range.location - 4;

            NSString *nextDigits = [textField.text substringWithRange:NSMakeRange(4, newLenght)];

            NSString *updatedText = [NSString stringWithFormat:@"%@%@%@",firstThree,dash,nextDigits];

            [textField setText:updatedText];

        }

    }

    else if ( currentLength == 8 ) 
    {

        if ( range.length != 1 ) 
        {
            NSString *areaCode = [textField.text substringWithRange:NSMakeRange(0, 3)];

            NSString *firstThree = [textField.text substringWithRange:NSMakeRange(4, 3)];

            NSString *nextDigit = [textField.text substringWithRange:NSMakeRange(7, 1)];

            [textField setText:[NSString stringWithFormat:@"(%@) %@-%@",areaCode,firstThree,nextDigit]];
        }

    }
}

else {
    return NO;
}

return YES;
}
于 2012-09-07T18:09:14.040 回答