iOS 上的电话号码格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6052966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Phone number formatting on iOS
提问by Moni Viki
I have a text field where the user enters data. It's a phone number field. If the user enters 1234567890
, I want it displayed as (123)-(456)-7890
as the user types. How is this possible?
我有一个用户输入数据的文本字段。这是一个电话号码字段。如果用户输入1234567890
,我希望它显示为(123)-(456)-7890
用户键入。这怎么可能?
回答by wan
This will help you
这会帮助你
Format (xxx) xxx-xxxx
格式(xxx)xxx-xxxx
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
int length = (int)[self getLength:textField.text];
//NSLog(@"Length = %d ",length);
if(length == 10)
{
if(range.length == 0)
return NO;
}
if(length == 3)
{
NSString *num = [self formatNumber:textField.text];
textField.text = [NSString stringWithFormat:@"(%@) ",num];
if(range.length > 0)
textField.text = [NSString stringWithFormat:@"%@",[num substringToIndex:3]];
}
else if(length == 6)
{
NSString *num = [self formatNumber:textField.text];
//NSLog(@"%@",[num substringToIndex:3]);
//NSLog(@"%@",[num substringFromIndex:3]);
textField.text = [NSString stringWithFormat:@"(%@) %@-",[num substringToIndex:3],[num substringFromIndex:3]];
if(range.length > 0)
textField.text = [NSString stringWithFormat:@"(%@) %@",[num substringToIndex:3],[num substringFromIndex:3]];
}
return YES;
}
- (NSString *)formatNumber:(NSString *)mobileNumber
{
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"(" withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@")" withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"+" withString:@""];
NSLog(@"%@", mobileNumber);
int length = (int)[mobileNumber length];
if(length > 10)
{
mobileNumber = [mobileNumber substringFromIndex: length-10];
NSLog(@"%@", mobileNumber);
}
return mobileNumber;
}
- (int)getLength:(NSString *)mobileNumber
{
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"(" withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@")" withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"+" withString:@""];
int length = (int)[mobileNumber length];
return length;
}
回答by bryguy1300
This felt more clear and handles removing any unwanted characters much more nicely. Formats correctly for 1?(###)?###?####or (###)?###?####
这感觉更清晰,并且可以更好地处理删除任何不需要的字符。格式正确为1?(###)?###?####或(###)?###?####
- (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;
}
回答by datinc
The code bellow is what I typically use. The format is different but you get the picture. This will handle input such as '123df#$@$gdfg45-+678dfg901' and output '1 (234) 567-8901'
下面的代码是我通常使用的。格式不同,但你得到了图片。这将处理诸如 '123df#$@$gdfg45-+678dfg901' 和输出 '1 (234) 567-8901' 之类的输入
#import "NSString+phoneNumber.h"
@implementation NSString (phoneNumber)
-(NSString*) phoneNumber{
static NSCharacterSet* set = nil;
if (set == nil){
set = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
}
NSString* phoneString = [[self componentsSeparatedByCharactersInSet:set] componentsJoinedByString:@""];
switch (phoneString.length) {
case 7: return [NSString stringWithFormat:@"%@-%@", [phoneString substringToIndex:3], [phoneString substringFromIndex:3]];
case 10: return [NSString stringWithFormat:@"(%@) %@-%@", [phoneString substringToIndex:3], [phoneString substringWithRange:NSMakeRange(3, 3)],[phoneString substringFromIndex:6]];
case 11: return [NSString stringWithFormat:@"%@ (%@) %@-%@", [phoneString substringToIndex:1], [phoneString substringWithRange:NSMakeRange(1, 3)], [phoneString substringWithRange:NSMakeRange(4, 3)], [phoneString substringFromIndex:7]];
case 12: return [NSString stringWithFormat:@"+%@ (%@) %@-%@", [phoneString substringToIndex:2], [phoneString substringWithRange:NSMakeRange(2, 3)], [phoneString substringWithRange:NSMakeRange(5, 3)], [phoneString substringFromIndex:8]];
default: return nil;
}
}
@end
回答by Michael Enriquez
We wrote a custom NSFormatter subclass for phone numbers here: https://github.com/edgecase/PhoneNumberFormatter
我们在这里为电话号码编写了一个自定义的 NSFormatter 子类:https: //github.com/edgecase/PhoneNumberFormatter
You can use it like any other NSFormatter subclass.
您可以像使用任何其他 NSFormatter 子类一样使用它。
回答by Yangel
Thanks so much for the first answer but, i think, that method -(int)getLength:(NSString*)mobileNumber
is useless. You can try something like below:
非常感谢您的第一个答案,但我认为该方法-(int)getLength:(NSString*)mobileNumber
没用。您可以尝试以下操作:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
int length = [[self formatNumber:[textField text]] length];
if (length == 10) {
if(range.length == 0) {
return NO;
}
}
if (length == 3) {
NSString *num = [self formatNumber:[textField text]];
textField.text = [NSString stringWithFormat:@"(%@) ",num];
if (range.length > 0) {
[textField setText:[NSString stringWithFormat:@"%@",[num substringToIndex:3]]];
}
}
else if (length == 6) {
NSString *num = [self formatNumber:[textField text]];
[textField setText:[NSString stringWithFormat:@"(%@) %@-",[num substringToIndex:3],[num substringFromIndex:3]]];
if (range.length > 0) {
[textField setText:[NSString stringWithFormat:@"(%@) %@",[num substringToIndex:3],[num substringFromIndex:3]]];
}
}
return YES;
}
- (NSString*)formatNumber:(NSString*)mobileNumber {
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"(" withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@")" withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"+" withString:@""];
int length = [mobileNumber length];
if (length > 10) {
mobileNumber = [mobileNumber substringFromIndex: length-10];
}
return mobileNumber;
}
回答by ekscrypto
For those of you who require international number formatting: https://code.google.com/p/libphonenumber/
对于那些需要国际号码格式的人:https: //code.google.com/p/libphonenumber/
Comes with C++, Java and JavaScript implementations. Should be easy to wrap the C++ implementations in a .mm file and write a small Objective-C wrapper around it.
附带 C++、Java 和 JavaScript 实现。将 C++ 实现包装在 .mm 文件中并在其周围编写一个小的 Objective-C 包装器应该很容易。
回答by Kappe
A valid option is https://github.com/iziz/libPhoneNumber-iOSAll the other answer cover only a small part of the possibilities and combinations, this library actually parse and validate EVERY phone number, and identify:
一个有效的选项是https://github.com/iziz/libPhoneNumber-iOS所有其他答案只涵盖了可能性和组合的一小部分,这个库实际上解析和验证每个电话号码,并识别:
- Nationality
- phone number type
- National carrier
- 国籍
- 电话号码类型
- 国家承运人
回答by rizk.taker
Relevant for U.S. Phone Numbers:
与美国电话号码相关:
Adding to @wan's post, I added a conditional statement if the user starts with the country code (1). That way, it will format to be: 1 (XXX) XXX-XXXX instead of (1XX) XXX-XXXX.
添加到@wan 的帖子中,如果用户以国家/地区代码 (1) 开头,我添加了一个条件语句。这样,它将格式为:1 (XXX) XXX-XXXX 而不是 (1XX) XXX-XXXX。
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
textField = self.phoneNumberTextField;
NSInteger length = [self getLength:textField.text];
//NSLog(@"Length = %d ",length);
if ([textField.text hasPrefix:@"1"]) {
if(length == 11)
{
if(range.length == 0)
return NO;
}
if(length == 4)
{
NSString *num = [self formatNumber:textField.text];
textField.text = [NSString stringWithFormat:@"%@ (%@) ",[num substringToIndex:1],[num substringFromIndex:1]];
if(range.length > 0)
textField.text = [NSString stringWithFormat:@"%@",[num substringToIndex:4]];
}
else if(length == 7)
{
NSString *num = [self formatNumber:textField.text];
NSRange numRange = NSMakeRange(1, 3);
textField.text = [NSString stringWithFormat:@"%@ (%@) %@-",[num substringToIndex:1] ,[num substringWithRange:numRange],[num substringFromIndex:4]];
if(range.length > 0)
textField.text = [NSString stringWithFormat:@"(%@) %@",[num substringToIndex:3],[num substringFromIndex:3]];
}
} else {
if(length == 10)
{
if(range.length == 0)
return NO;
}
if(length == 3)
{
NSString *num = [self formatNumber:textField.text];
textField.text = [NSString stringWithFormat:@"(%@) ",num];
if(range.length > 0)
textField.text = [NSString stringWithFormat:@"%@",[num substringToIndex:3]];
}
else if(length == 6)
{
NSString *num = [self formatNumber:textField.text];
textField.text = [NSString stringWithFormat:@"(%@) %@-",[num substringToIndex:3],[num substringFromIndex:3]];
if(range.length > 0)
textField.text = [NSString stringWithFormat:@"(%@) %@",[num substringToIndex:3],[num substringFromIndex:3]];
}
}
return YES;
}
-(NSString*)formatNumber:(NSString*)mobileNumber
{
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"(" withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@")" withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"+" withString:@""];
NSLog(@"%@", mobileNumber);
NSInteger length = [mobileNumber length];
if(length > 10)
{
mobileNumber = [mobileNumber substringFromIndex: length-10];
NSLog(@"%@", mobileNumber);
}
return mobileNumber;
}
-(NSInteger)getLength:(NSString*)mobileNumber
{
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"(" withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@")" withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
mobileNumber = [mobileNumber stringByReplacingOccurrencesOfString:@"+" withString:@""];
NSInteger length = [mobileNumber length];
return length;
}
回答by yunhasnawa
Maybe you could use this simple method:
也许你可以使用这个简单的方法:
+ (NSString*) formatPhoneNumber:(NSString *)phoneNumber codeLength:(int) code segmentLength:(int) segment
{
NSString* result = @"";
int length = [phoneNumber length];
NSString* firstSegment = @"";
NSString* restSegment = @"";
for (int i=0; i<length; i++) {
char c = [phoneNumber characterAtIndex:i];
if(i < code)
firstSegment = [firstSegment stringByAppendingFormat:@"%c", c];
else
{
restSegment = [restSegment stringByAppendingFormat:@"%c", c];
int threshold = (i - code) + 1;
if((threshold % segment == 0) && (threshold > 0) && !(threshold > length))
restSegment = [restSegment stringByAppendingFormat:@"%c", '-'];
}
}
result = [result stringByAppendingFormat:@"%@-%@", firstSegment, restSegment];
return result;
}
Assuming above method is in Contact
class, just use the method like this:
假设上面的方法是在Contact
类中,只需使用这样的方法:
NSString* phoneNumber = @"085755023455";
NSString* formattedNumber = [Contact formatPhoneNumber:phoneNumber codeLength:3 segmentLength:4];
That would be resulting something like:
这将导致类似:
085-7550-2345-5
回答by Dharmbir Singh
SWIFT
迅速
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let length = self.getTextLength(textField.text)
if length == 10{
if range.length == 0{
return false
}
}
if length == 3{
var num : String = self.formatNumber(textField.text)
textField.text = num + "-"
if(range.length > 0){
textField.text = (num as NSString).substringToIndex(3)
}
}
else if length == 6{
var num : String = self.formatNumber(textField.text)
let prefix = (num as NSString).substringToIndex(3)
let postfix = (num as NSString).substringFromIndex(3)
textField.text = prefix + "-" + postfix + "-"
if range.length > 0{
textField.text = prefix + postfix
}
}
return true
}
func getTextLength(mobileNo: String) -> NSInteger{
var str : NSString = mobileNo as NSString
str = str.stringByReplacingOccurrencesOfString("(", withString: "")
str = str.stringByReplacingOccurrencesOfString(")", withString: "")
str = str.stringByReplacingOccurrencesOfString(" ", withString: "")
str = str.stringByReplacingOccurrencesOfString("-", withString: "")
str = str.stringByReplacingOccurrencesOfString("+", withString: "")
return str.length
}
func formatNumber(mobileNo: String) -> String{
var str : NSString = mobileNo as NSString
str = str.stringByReplacingOccurrencesOfString("(", withString: "")
str = str.stringByReplacingOccurrencesOfString(")", withString: "")
str = str.stringByReplacingOccurrencesOfString(" ", withString: "")
str = str.stringByReplacingOccurrencesOfString("-", withString: "")
str = str.stringByReplacingOccurrencesOfString("+", withString: "")
if str.length > 10{
str = str.substringFromIndex(str.length - 10)
}
return str as String
}