动态格式化基于正则表达式的电话号码

时间:2016-09-06 10:57:21

标签: ios uitextfield

我需要实时格式化和更新UITextField以匹配给定的正则表达式,当用户输入并预填充正确的字符(例如连字符)时。

例如:当格式应为###-###-####和正则表达式^\d{3}-\d{3}-\d{4}$时,应在键入的第三和第七位数后动态地将连字符添加到UITextField

将来必须可以扩展不同的正则表达式。

任何想法如何做到这一点?

2 个答案:

答案 0 :(得分:0)

您应该查看UITextField委托方法shouldChangeCharactersInRange,然后您可以在其中输入当前range.location3 or 7的条件,然后添加hyphen那个地方并将当前字符串添加到下一个!

答案 1 :(得分:0)

您可以使用此代码为文本字段添加委托方法

  - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSInteger moddedLength = textField.text.length-(range.length-string.length);
    if (moddedLength >= 13) {
        return NO;
    }
    if (range.length == 0 &&![[NSCharacterSet decimalDigitCharacterSet] characterIsMember:[string characterAtIndex:0]]) {
        return NO;
    }
    if ([self range:range ContainsLocation:3] || [self range:range ContainsLocation:7]|| [self range:range ContainsLocation:9])
    {
        textField.text = [self formatPhoneString:[textField.text stringByReplacingCharactersInRange:range withString:string]];
        return NO;
    }
    return YES;
}

添加了此格式化方法

-(NSString*) formatPhoneString:(NSString*) preFormatted
{
    NSString* workingString = [preFormatted stringByReplacingOccurrencesOfString:@"-" withString:@""];
    if(workingString.length > 3) {
        workingString = [workingString stringByReplacingCharactersInRange:NSMakeRange(3, 0) withString:@"-"];
    }
    if(workingString.length > 7)
    {
        workingString = [workingString stringByReplacingCharactersInRange:NSMakeRange(7, 0) withString:@"-"];
    }
    if(workingString.length >11)
    {
        workingString = [workingString stringByReplacingCharactersInRange:NSMakeRange(3, 0) withString:@"-"];
    }
    return workingString;

}

-(bool) range:(NSRange) range ContainsLocation:(NSInteger) location {
    if(range.location <= location && range.location+range.length >= location)
    {
        return true;
    }
    return false;
}