以美国电话号码格式格式化 UILabel 内容

Posted

技术标签:

【中文标题】以美国电话号码格式格式化 UILabel 内容【英文标题】:Formatting UILabel contents in US phone number format 【发布时间】:2013-09-03 17:11:43 【问题描述】:

注意:因为我已经发布了这个问题,所以我这里是晚上。如果我没有回复 cmets 或答案,我会在早上做。感谢您的理解:-)

这个想法是在用户触摸每个 UIButton 时将 UILabel 格式化为电话号码(美国格式)。

有一个键盘布局,当用户触摸每个数字键时,标签会显示它并即时格式化生成的字符串。我写了一段我不是很自豪的代码。我希望有人能以更好的方式或不同的方法帮助我做到这一点。

图片应该让您大致了解它的外观。现在,进入逻辑:

在下面的代码中,keyOne 是将数字附加到 UILabel 的 IBAction,keyBack 是删除它的 IBAction。

这就是输入电话号码的工作原理:

如果我输入1234567890:

after 1,2,3 the label is modified as 123- and gets assigned to string
Now string will be 123- and I continue touching 4567890

after 123-4567, when I touch 8, label is modified as (123)456-78 and gets assigned to string
Now string will be (123)456-7890

If I wish, I could continue entering more numbers. 
As per requirement, the number should lose its formatting. 
i.e. After (123)456-7890 if I press 1, it should become 12345678901

现在,诀窍是以完全相同的方式撤消这些步骤。这里是泡菜。 如果我只输入 1234567890,_phoneNumber.text 将是 (123)456-7890,按三下应该会导致 123-4567。然后按四次返回应该是 123

但是,如果我输入 12345678901,_phoneNumber.text 将转到 (123)456-7890,然后失去格式变为 12345678901,当我按回一次时,它应该变为 (123)456-7890,依此类推。

如果您创建一个单视图应用程序类型的新项目并粘贴下面的内容(当然,在创建按钮并将 0-9 与 keyOne 连接后,使用 keyBack 返回)您会发现它工作正常。但正如我上面提到的,我写了一段我并不十分自豪的代码。我觉得应该有更简单的方法来做到这一点。

ViewController.h

@interface ViewController : UIViewController

@property (weak, nonatomic) IBOutlet UILabel *lengthParam;
@property (weak, nonatomic) IBOutlet UILabel *phoneNumber;
- (IBAction)keyOne:(id)sender;
- (IBAction)keyBack:(id)sender;
- (IBAction)clearAll:(id)sender;
@end

ViewController.m

#import "ViewController.h"

@interface ViewController () 
    BOOL isReformatted;

@end

@implementation ViewController

- (void)viewDidLoad 
    [super viewDidLoad];


- (void)didReceiveMemoryWarning 
    [super didReceiveMemoryWarning];


- (IBAction)keyOne:(id)sender 
    UIButton *btn = (UIButton *)sender;
    NSString *str = [NSString stringWithString:self.phoneNumber.text];
    str = [str stringByAppendingString:btn.titleLabel.text];
    self.phoneNumber.text = str;
    if(str.length==4) self.phoneNumber.text = [self insertMinus:str]; //before the 4th number, insert '-' as a first step
    if(str.length==9) self.phoneNumber.text = [self insertParenthesis:str]; //remove - before the 4th number, encapsulate first 3 numbers inside () and add - at end of current number
    if(str.length>13) self.phoneNumber.text = [self plainFormat:str]; //if user enter more than 10 numbers, remove formatting
    self.lengthParam.text = [NSString stringWithFormat:@"%d",self.phoneNumber.text.length];


- (IBAction)keyBack:(id)sender 
    NSString *str = [NSString stringWithString:self.phoneNumber.text];
    NSString *newStr = nil;
    if(str.length>0)  //check for empty string
        if(str.length>11 && isReformatted==NO) newStr = [str substringToIndex:str.length-1]; //string.length > 10 which means plainFormat was called earlier and reFormat isn't called yet
        else if(str.length==11 && isReformatted == NO)  //string length is now 11
            if([str characterAtIndex:0]!='(') newStr = [self reFormat:str]; //if entered string is 12345678901, it is not reFormatted. remove last 1 and reFormat it as (123)456-7890
            else newStr = [self removeParenthesis:str]; //entered string itself is (123)456-78 so transform it as 123-4567
         else  //we are dealing with a reformatted string of length 11 now.
            newStr = [str substringToIndex:str.length-1]; //String is (123)456-78, remove 8 and apply one of the below rules
            if(newStr.length==10)  //transform (123)456-7 as 123-4567
                newStr = [str substringToIndex:str.length-1];
                newStr = [self removeParenthesis:str];
            
            if(newStr.length==4&&[newStr characterAtIndex:3]=='-') newStr = [self removeMinus:str]; //transform 123-4 to 123
        
        self.phoneNumber.text = newStr;
        self.lengthParam.text = [NSString stringWithFormat:@"%d",self.phoneNumber.text.length];
    


- (IBAction)clearAll:(id)sender 
    self.phoneNumber.text = @"";
    self.lengthParam.text = [NSString stringWithFormat:@"%d",self.phoneNumber.text.length];


- (NSString *)insertMinus:(NSString *)str 
    return [NSString stringWithFormat:@"%@-%@",[str substringToIndex:3],[str substringFromIndex:3]];


- (NSString *)insertParenthesis:(NSString *)str 
    NSString *c1 = [NSString stringWithFormat:@"(%@)",[str substringToIndex:3]];
    NSString *c2 = [NSString stringWithFormat:@"%@-%@",[str substringWithRange:NSMakeRange(4, 3)],[str substringFromIndex:7]];
    return [NSString stringWithFormat:@"%@%@",c1,c2];


- (NSString *)plainFormat:(NSString *)str 
    isReformatted = NO;
    str = [str stringByReplacingOccurrencesOfString:@"(" withString:@""];
    str = [str stringByReplacingOccurrencesOfString:@")" withString:@""];
    str = [str stringByReplacingOccurrencesOfString:@"-" withString:@""];
    str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    return str;


- (NSString *)reFormat:(NSString *)str 
    isReformatted = YES;
    NSString *c1 = [NSString stringWithFormat:@"(%@)",[str substringToIndex:3]];
    NSString *c2 = [NSString stringWithFormat:@"%@-%@",[str substringWithRange:NSMakeRange(3, 3)],[str substringWithRange:NSMakeRange(6, 4)]];
    return [NSString stringWithFormat:@"%@%@",c1,c2];


- (NSString *)removeParenthesis:(NSString *)str 
    str = [self plainFormat:str];
    NSString *newStr = [NSString stringWithFormat:@"%@-%@",[str substringToIndex:3],[str substringWithRange:NSMakeRange(3, 4)]];
    return newStr;


- (NSString *)removeMinus:(NSString *)str 
    str = [self plainFormat:str];
    NSString *newStr = [NSString stringWithFormat:@"%@",[str substringToIndex:3]];
    return newStr;


@end

【问题讨论】:

您是否检查过 AddressBook 框架以查看是否有提供此功能的东西? github.com/edgecase/PhoneNumberFormatter @nielsbot 您可以使用通讯簿框架检索电话号码.. 不格式化:-( @Marco 谢谢 :-) 但我想有自己的解决方案 :-) 【参考方案1】:

如果您渴望走上自己的电话号码格式化程序的道路,我会考虑执行以下操作:

    将用户输入存储在字符串中而不进行格式化。 每次按键后,重新格式化显示字符串。

类似:

@property (nonatomic, copy) NSMutableString *backingString;
@property (weak, nonatomic) IBOutlet UILabel *phoneNumber;

- (void)viewWillAppear:(BOOL)animated

   [super viewWillAppear:animated];
   backingString = [NSMutableString string];


- (IBAction)keyOne:(id)sender

    UIButton *btn = (UIButton *)sender;
    [self.backingString appendString:btn.titleLabel.text];
    [self formatBackingString];



- (IBAction)keyBack:(id)sender

    [self.backingString deleteCharactersInRange:(NSRange)self.backingString.length - 1,1];
    [self formatBackingString];


- (void)formatBackingString

    // Do your phone formatting here
    NSMutableString *formattedString = [NSMutableString string];
    NSInteger length = self.backingString.length;
    if (length < 3)
    
       [formattedString appendString:self.backingString];
    
    else if (length == 3)
    
       [formattedString appendFormat:@"%@-", self.backingString];
    
    else if (length < 8)
    
        // etc...
    
    self.phoneNumber.text = formattedString;

你也可以看看NSNumberFormatter。

【讨论】:

谢谢,但是如何以我以更简单的方式发布的方式执行 formatBackingString 是问题:-( @thandasoru 你这样做的方式是只保留格式化的字符串。这让你的生活变得更加困难。我将编辑我的答案。 感谢您的更新。我会试试这个并在这里添加我的评论。 虽然代码不是一个明确的答案,但它向我展示了一种解决问题的新方法。我可以在触摸时格式化数字,但无法以应该删除的方式删除数字。也感谢您的链接! 很高兴它有帮助。无论是通过添加数字还是删除数字,您总是以相同的方式格式化数字吗?如果按删除从您的支持字符串中删除最后一个字符,您的格式化方法应该能够产生正确的格式,我想。无论如何,祝你好运。

以上是关于以美国电话号码格式格式化 UILabel 内容的主要内容,如果未能解决你的问题,请参考以下文章

获取美国格式的用户电话号码

JavaScript 正则表达式用 n 任何字符格式化电话以进行扩展

如何将字符串号码格式化为美国电话号码格式

php 格式化美国电话号码

格式化美国电话号码

用于验证美国电话号码格式的 RegEx