前一陣子項(xiàng)目遇到一個(gè)需求:標(biāo)簽展現(xiàn)的文字中需要識(shí)別手機(jī)號(hào)碼播玖,高亮顯示添加下劃線并可以點(diǎn)擊撥打電話。
直接上代碼,寫了一個(gè)方法古话,傳入需要進(jìn)行判斷的標(biāo)簽及其標(biāo)簽的文字內(nèi)容
-(void)distinguishPhoneNumLabel:(UILabel *)label labelStr:(NSString *)labelStr{
//獲取字符串中的電話號(hào)碼
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;
//定義一個(gè)NSAttributedstring接受電話號(hào)碼字符串
phoneNumber = [str attributedSubstringFromRange:phoneRange];
//添加下劃線
NSDictionary *attribtDic = @{NSUnderlineStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
[str addAttributes:attribtDic range:phoneRange];
//設(shè)置文本中的電話號(hào)碼顯示為黃色
[str addAttribute:NSForegroundColorAttributeName value:[LFWImage colorWithHexString:@"FF8200"] range:phoneRange];
label.attributedText = str;
label.userInteractionEnabled = YES;
//添加手勢(shì)顶掉,可以點(diǎn)擊號(hào)碼撥打電話
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGesture:)];
[label addGestureRecognizer:tap];
}];
}
}
//實(shí)現(xiàn)撥打電話的方法
-(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:@"您的設(shè)備不能打電話" delegate:nil cancelButtonTitle:@"好的,知道了" otherButtonTitles:nil,nil];
[alert show];
}else{
//NSAttributedstring轉(zhuǎn)換為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];
}
}