简体   繁体   中英

How to format UITextfield to take a phone number string in iOS

I have a UITextfield that takes a string value

I would like the UITextfield to format the string entered as ###-###-#### The limit is 10 digits. Nothing below 10 digits will be accepted. If a user accidentally typed in the wrong number, the user can delete a number and the formatter should still work.

The string should save as "###-###-####" format, so example would be 213-222-0387

If anyone can help, I would greatly appreciate it!

Try this:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    NSArray *components = [newString componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
    NSString *decimalString = [components componentsJoinedByString:@""];

    NSUInteger length = decimalString.length;
    BOOL hasLeadingOne = length > 0 && [decimalString characterAtIndex:0] == '1';

    if (length == 0 || (length > 10 && !hasLeadingOne) || (length > 11)) {
        textField.text = decimalString;
        return NO;
    }

    NSUInteger index = 0;
    NSMutableString *formattedString = [NSMutableString string];

    if (hasLeadingOne) {
        [formattedString appendString:@"1 "];
        index += 1;
    }

    if (length - index > 3) {
        NSString *areaCode = [decimalString substringWithRange:NSMakeRange(index, 3)];
        [formattedString appendFormat:@"%@-",areaCode];
        index += 3;
    }

    if (length - index > 3) {
        NSString *prefix = [decimalString substringWithRange:NSMakeRange(index, 3)];
        [formattedString appendFormat:@"%@-",prefix];
        index += 3;
    }

    NSString *remainder = [decimalString substringFromIndex:index];
    [formattedString appendString:remainder];

    textField.text = formattedString;

    return NO;
}

Here's a simple method that will take any 10-char string and reformat it in the format you specified. However, this method a little oversimplified as it won't check the 10 characters to make sure they are all digits, nor would it update the string within the text field as it is being input if that is what you want. The upside is that its easily modifiable if you want to account for locations with different phone number formats. Assuming your app's users are only in CA/US, this should suffice, but if not you could just add some conditional logic and modify the code accordingly.

- (NSString *)formattedPhoneNumberStringFromTenDigitString: (NSString *)unformattedString {
NSString *formattedPhoneNumberString;
if (unformattedString.length == 10) {
    NSString *firstThreeDigitString = [unformattedString substringWithRange: NSMakeRange(0, 3)];
    NSString *secondThreeDigitString = [unformattedString substringWithRange: NSMakeRange(3, 3)];
    NSString *finalFourDigitString = [unformattedString substringWithRange: NSMakeRange(6, 4)];
    formattedPhoneNumberString = [NSString stringWithFormat:@"%@-%@-%@", firstThreeDigitString, secondThreeDigitString, finalFourDigitString];
    NSLog(@"formattedPhoneNumerString: %@", formattedPhoneNumberString);
}

if (formattedPhoneNumberString) {
    return formattedPhoneNumberString;
}
else {
    NSLog(@"Phone-number entry text-field != 10 chars");
    return nil;
}}

This code works for me, hope it works for you too,

-(NSString*) formatPhoneNumber:(NSString *)phoneString{

    NSString *phoneNumber = [[phoneString componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:@""];
    switch (phoneNumber.length) {
        case 7: return [NSString stringWithFormat:@"%@-%@", [phoneNumber substringToIndex:3], [phoneNumber substringFromIndex:3]];
        case 10: return [NSString stringWithFormat:@"(%@) %@-%@", [phoneNumber substringToIndex:3], [phoneNumber substringWithRange:NSMakeRange(3, 3)],[phoneNumber substringFromIndex:6]];
        case 11: return [NSString stringWithFormat:@"%@ (%@) %@-%@", [phoneNumber substringToIndex:1], [phoneNumber substringWithRange:NSMakeRange(1, 3)], [phoneNumber substringWithRange:NSMakeRange(4, 3)], [phoneNumber substringFromIndex:7]];
        case 12: return [NSString stringWithFormat:@"+%@ (%@) %@-%@", [phoneNumber substringToIndex:2], [phoneNumber substringWithRange:NSMakeRange(2, 3)], [phoneNumber substringWithRange:NSMakeRange(5, 3)], [phoneNumber substringFromIndex:8]];
        default: return [NSString stringWithFormat:@"(%@) %@-%@", [phoneNumber substringToIndex:3], [phoneNumber substringWithRange:NSMakeRange(3, 3)],[phoneNumber substringFromIndex:6]];
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM