NSNumberFormatter格式化美国电话号码

sam*_*sam 8 iphone cocoa cocoa-touch objective-c

我正在尝试将用户输入的一串数字转换为iPhone上的Phone.app等性感字符串.这是我正在使用的代码,它不起作用(没有特殊格式出现),并且在一定数量的数字后,它只是开始在字符串的末尾添加"0".

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterNoStyle];
[formatter setPositiveFormat:@"+# (###) ###-###"];
[formatter setLenient:YES];
NSString *strDigits = [self stringByReplacingOccurrencesOfRegex:@"[^0-9+]" withString:@""];
return [formatter stringFromNumber:[NSNumber numberWithDouble:[strDigits doubleValue]]];
Run Code Online (Sandbox Code Playgroud)

Dan*_*n J 11

我认为你的问题是NSNumberFormatter不支持括号,空格或破折号.我试图实现与您相同的方法,它无声地失败,只输出未格式化的文本.

这里的一般问题是iPhone SDK没有提供以区域设置相关方式格式化电话号码的方法.

我已经向Apple提出了以下错误(其中两个是已知问题的重复,所以我已经包含了Apple的原始bug#):

#6933244 - Need iPhone SDK interface to format text as locale dependent phone number
#5847381 - UIControl does not support a setFormatter method
#6024985 - Overridden UITextField drawTextInRect method is never called
Run Code Online (Sandbox Code Playgroud)

在一个理想的世界里,Apple会提供一个NSPhoneNumberFormatter,你会打电话setFormatter给你,UIControl所以它text以漂亮的方式展示.不幸的是,iPhone上并不存在.


Ahm*_*der 9

UIPhoneFormats.plist包含每个语言环境的预定义电话格式.因此,如果您只对美国电话号码感兴趣,则需要考虑以下格式:

+1(###)### - ####
1(###)### - ####
011 $
### - ####
(###)### - ## ##

我不得不做类似的事情,我分享了我在这里得到的结果:http: //the-lost-beauty.blogspot.com/2010/01/locale-sensitive-phone-number.html