前一阵子项目遇到一个需求:标签展现的文字中需要识别手机号码,高亮显示添加下划线并可以点击拨打电话。
直接上代码,写了一个方法,传入需要进行判断的标签及其标签的文字内容
-(void)distinguishPhoneNumLabel:(UILabel *)label labelStr:(NSString *)labelStr{
//获取字符串中的电话号码
NSString *regulaStr = @"\\d{3,4}[- ]?\\d{7,8}";
NSRange stringRange = NSMakeRange(0, labelStr.length);
//正则匹配
NSError *error;
NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:labelStr];
NSRegularExpression *regexps = [NSRegularExpression regularExpressionWithPattern:regulaStr options:0 error:&error];
if (!error && regexps != nil) {
[regexps enumerateMatchesInString:labelStr options:0 range:stringRange usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {
NSRange phoneRange = result.range;
//定义一个NSAttributedstring接受电话号码字符串
phoneNumber = [str attributedSubstringFromRange:phoneRange];
//添加下划线
NSDictionary *attribtDic = @{NSUnderlineStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
[str addAttributes:attribtDic range:phoneRange];
//设置文本中的电话号码显示为黄色
[str addAttribute:NSForegroundColorAttributeName value:[LFWImage colorWithHexString:@"FF8200"] range:phoneRange];
label.attributedText = str;
label.userInteractionEnabled = YES;
//添加手势,可以点击号码拨打电话
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGesture:)];
[label addGestureRecognizer:tap];
}];
}
}
//实现拨打电话的方法
-(void)tapGesture:(UITapGestureRecognizer *)sender{
NSString *deviceType = [UIDevice currentDevice].model;
if([deviceType isEqualToString:@"iPod touch"]||[deviceType isEqualToString:@"iPad"]||[deviceType isEqualToString:@"iPhone Simulator"]){
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:@"您的设备不能打电话" delegate:nil cancelButtonTitle:@"好的,知道了" otherButtonTitles:nil,nil];
[alert show];
}else{
//NSAttributedstring转换为NSString
NSString *stringNum = [phoneNumber string];
NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",stringNum];
NSString *newStr = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
UIWebView * callWebview = [[UIWebView alloc] init];
[callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:newStr]]];
[self.view addSubview:callWebview];
}
}