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

时间:2013-09-03 17:11:44

标签: ios objective-c nsstring

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

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

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

screen

图像应该让您对它的外观有一个很好的了解。现在,进入逻辑:

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

这就是输入电话号码的方式:

如果我输入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,依此类推。 / p>

如果您打造一个类型为单一视图应用程序的新项目并粘贴下面的内容,(当然在创建按钮并使用keyOne连接0-9,然后使用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

1 个答案:

答案 0 :(得分:1)

如果您急于推动自己的电话号码格式化,请考虑采取以下措施:

  1. 将用户输入存储而不格式化为字符串。
  2. 每次按键后,重新格式化显示字符串。
  3. 类似的东西:

    @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