0

iPhoneの連絡先テーブルビューには「電話」と呼ばれるセルがあり、ユーザーがこの携帯電話番号を編集すると、(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 に答える