简体   繁体   中英

String to Phone Number format on iOS

In my app, I have a string like:

"3022513240"

I want to convert this like:

(302)-251-3240

How can I solve this?

I would do this way:

Example:

 NSMutableString *stringts = [NSMutableString stringWithString:self.ts.text];
 [stringts insertString:@"(" atIndex:0];
 [stringts insertString:@")" atIndex:4];
 [stringts insertString:@"-" atIndex:5];
 [stringts insertString:@"-" atIndex:9];
 self.ts.text = stringts;

Hope this helps...

Here is a Swift extension that formats strings into phone numbers for 10 digit numbers.

extension String {    
    public func toPhoneNumber() -> String {
        return stringByReplacingOccurrencesOfString("(\\d{3})(\\d{3})(\\d+)", withString: "($1) $2-$3", options: .RegularExpressionSearch, range: nil)
    }
}

For example:

let number = "1234567890"
let phone = number.toPhoneNumber()
print(phone)
// (123) 456-7890

Updated to Swift 3.0 :

extension String {
    public func toPhoneNumber() -> String {
        return self.replacingOccurrences(of: "(\\d{3})(\\d{3})(\\d+)", with: "($1) $2-$3", options: .regularExpression, range: nil)
    }
}

You can use this way

NSError *aError = nil;
NBPhoneNumber *myNumber1 = [phoneUtil parse:@"6766077303" defaultRegion:@"AT" error:&aError];
if (aError == nil)
{
    NSLog(@"isValidPhoneNumber ? [%@]", [phoneUtil isValidNumber:myNumber1] ? @"YES":@"NO");
    NSLog(@"E164          : %@", [phoneUtil format:myNumber1 numberFormat:NBEPhoneNumberFormatE164]);
    NSLog(@"INTERNATIONAL : %@", [phoneUtil format:myNumber1 numberFormat:NBEPhoneNumberFormatINTERNATIONAL]);
    NSLog(@"NATIONAL      : %@", [phoneUtil format:myNumber1 numberFormat:NBEPhoneNumberFormatNATIONAL]);
    NSLog(@"RFC3966       : %@", [phoneUtil format:myNumber1 numberFormat:NBEPhoneNumberFormatRFC3966]);
}
else
{
    NSLog(@"Error : %@", [aError localizedDescription]);
}

您可以使用像(\\d{3})(\\d{3})(\\d{4})这样的正则表达式,并将符合该模式的输入替换为($1)-$2-$3

Swift 4.2

extension String {
public func toPhoneNumber() -> String {
    return self.replacingOccurrences(of: "(\\d{3})(\\d{3})(\\d+)", with: "$1-$2-$3", options: .regularExpression, range: nil)
}}

Result

结果

You could use RMPhoneFormat library for formatting phone numbers. The formatting should replicate what you would see in the Contacts app for the same phone number.

This is the simple and easy

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
   if (string.length) {
       if (textField.text.length<=13) {
           if (textField.text.length==3) {
               NSString *tempStr=[NSString stringWithFormat:@"(%@)- ",textField.text];
               textField.text=tempStr;
           } else if (textField.text.length==8) {
               NSString *tempStr=[NSString stringWithFormat:@"%@-",textField.text];
               textField.text=tempStr;
           }
       } else {
           return NO;
       }
   }
   return YES;
}

Lookup RMPhoneFormat ,我用它很棒。

I used the SHSPhoneNumberFormatter to do this so I don't have to change the type or subclass my UITextField

To set it up:

let phoneNumberFormatter = SHSPhoneNumberFormatter()
phoneNumberFormatter.setDefaultOutputPattern("(###) ###-####")

Listen for the UITextFieldTextDidChangeNotification and run the following:

let phoneDict = phoneNumberFormatter.valuesForString(phoneTextField.text) 
phoneTextField.text = phoneDict["text"] as? String

Here is a code to convert string to phone number format

Swift 3

func PhoneNumberFormate( str : NSMutableString)->String{
        str.insert("(", at: 0)
        str.insert(")", at: 4)
        str.insert("-", at: 8)
        return str as String
    }

to use

let nsMutableString = NSMutableString(string: "3022513240")
let strModify = self.PhoneNumberFormate(str: nsMutableString)

Swift 4.2

Handles 10 and 11 digit phone numbers that may or may not already have formatting or non-digit characters in the string.

Will handle:

  • 1234567890, 12345678901, 123 456 7890, 123-456-7890, (123) 456-7890, 1-234-567-8901

Result:

  • (999)-999-9999
  • 1(999)-999-9999

Code:

extension String {

    /// Handles 10 or 11 digit phone numbers
    ///
    /// - Returns: formatted phone number or original value
    public func toPhoneNumber() -> String {
        let digits = self.digitsOnly
        if digits.count == 10 {
            return digits.replacingOccurrences(of: "(\\d{3})(\\d{3})(\\d+)", with: "($1)-$2-$3", options: .regularExpression, range: nil)
        }
        else if digits.count == 11 {
            return digits.replacingOccurrences(of: "(\\d{1})(\\d{3})(\\d{3})(\\d+)", with: "$1($2)-$3-$4", options: .regularExpression, range: nil)
        }
        else {
            return self
        }
    }

}

extension StringProtocol {

    /// Returns the string with only [0-9], all other characters are filtered out
    var digitsOnly: String {
        return String(filter(("0"..."9").contains))
    }

}

Example:

let num = "1234567890"
let formatted = num.toPhoneNumber()
// Formatted is "(123)-456-7890"
NSString* formatPhoneNumber(NSString* phoneNumber, NSString *mask) {
    // Remove any non-numeric characters from the phone number string
    NSString* strippedNumber = [[phoneNumber componentsSeparatedByCharactersInSet:
                                [[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
                               componentsJoinedByString:@""];
    // Check if the phone number is the correct length
    if (strippedNumber.length != [mask componentsSeparatedByString:@"X"].count) {
        return phoneNumber;
    }
    // Initialize a string for the formatted phone number
    NSString* formattedNumber = mask;
    int i = 0;
    // Iterate through the mask, replacing "X" with corresponding digits
    for (NSUInteger j = 0; j < formattedNumber.length; j++) {
        if ([formattedNumber characterAtIndex:j] == 'X') {
            formattedNumber = [formattedNumber stringByReplacingCharactersInRange:NSMakeRange(j, 1) withString:[strippedNumber substringWithRange:NSMakeRange(i, 1)]];
            i++;
        }
    }
    return formattedNumber;
}

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