因为要做物流信息展示,展示相关快递信息等,可能会有电话、座机号等联系方式,要求可点击并能打电话。
开始网上找的一个,如下:
-(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];
NSInteger matches = [regexps numberOfMatchesInString:labelStr options:0 range:NSMakeRange(0, labelStr.length)];
if (matches > 0) {
}else
{
label.text = labelStr;
return;
}
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];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"#eb2323"] range:phoneRange];
[str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13] range:phoneRange];
label.attributedText = str;
label.userInteractionEnabled = YES;
//添加手势,可以点击号码拨打电话
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGesture:)];
[label addGestureRecognizer:tap];
}];
}
}
这个可以实现文字中 有一个电话号码,并且只能匹配手机号。
如果有多个手机号,或者参杂座机号就会有问题,只能匹配到一个手机号。
然后,改用以下方法便可以解决以上问题。
☺️☺️☺️☺️☺️☺️☺️☺️☺️☺️☺️☺️☺️☺️☺️☺️☺️☺️☺️☺️☺️
首先添加头文件 #import "YYText.h"
, #import "NSString+phone.h"
,添加宏 #define PHONEREGULAR @"\\d{3,4}[- ]?\\d{7,8}"//匹配10到12位连续数字,或者带连字符/空格的固话号,空格和连字符可以省略。
创建分类NSString+phone.h,添加方法
+ (BOOL)isMobilePhoneOrtelePhone:(NSString *)mobileNum;
用于验证是否手机号或者固话。
+ (BOOL)isMobilePhoneOrtelePhone:(NSString *)mobileNum {
if (mobileNum==nil || mobileNum.length ==0) {
return NO;
}
/**
* 手机号码
* 移动:134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
* 联通:130,131,132,152,155,156,185,186
* 电信:133,1349,153,180,189
*/
NSString * MOBILE = @"^((13)|(14)|(15)|(17)|(18))\\d{9}$";// @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
/**
10 * 中国移动:China Mobile
11 * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
12 */
NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[23478])\\d)\\d{7}$";
/**
15 * 中国联通:China Unicom
16 * 130,131,132,152,155,156,185,186
17 */
NSString * CU = @"^1(3[0-2]|5[256]|7[01678]|8[56])\\d{8}$";
/**
20 * 中国电信:China Telecom
21 * 133,1349,153,180,189
22 */
NSString * CT = @"^1((33|53|8[019])[0-9]|349)\\d{7}$";
/**
25 * 大陆地区固话及小灵通
26 * 区号:010,020,021,022,023,024,025,027,028,029
27 * 号码:七位或八位
28 */
NSString * PHS = @"^((0\\d{2,3}-?)\\d{7,8}(-\\d{2,5})?)$";// @"^0(10|2[0-5789]-|\\d{3})\\d{7,8}$";
NSString *GH = @"^400-([0-9]){1}([0-9-]{7})$";
NSPredicate *regextestPHS = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", PHS];
NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
NSPredicate *regextestGH = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", GH];
if (([regextestmobile evaluateWithObject:mobileNum] == YES)
|| ([regextestcm evaluateWithObject:mobileNum] == YES)
|| ([regextestct evaluateWithObject:mobileNum] == YES)
|| ([regextestcu evaluateWithObject:mobileNum] == YES)
|| ([regextestPHS evaluateWithObject:mobileNum]==YES)
|| ([regextestGH evaluateWithObject:mobileNum] == YES)) {
return YES;
}
else{
return NO;
}
}
重点来了,创建label,进行赋值、匹配:
- (void)reloadDataWithModel:(YYOderExpressVo*)model {
for (UIView *temp in self.subviews) {
if ([temp isKindOfClass:[YYLabel class]]) {
[temp removeFromSuperview];
}
}
YYLabel * label = [[YYLabel alloc]initWithFrame:CGRectMake(_detailLabel.frame.origin.x, _detailLabel.frame.origin.y, SCREEN_WIDTH-61, _detailHeightConstant.constant)];
label.numberOfLines = 0;
[self addSubview:label];
NSRange stringRange = NSMakeRange(0, model.message.length);
//正则匹配
NSError *error;
NSRegularExpression *regexps = [NSRegularExpression regularExpressionWithPattern:PHONEREGULAR options:0 error:&error];
// 转为富文本
NSMutableAttributedString *dsc = [[NSMutableAttributedString alloc]initWithString:model.message];
// NSFontAttributeName
[dsc addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13] range:NSMakeRange(0, model.message.length)];
[dsc addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"#999999"] range:NSMakeRange(0, model.message.length)];
if (!error && regexps != nil) {
[regexps enumerateMatchesInString:model.message options:0 range:stringRange usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {
//可能为电话号码的字符串及其所在位置
NSMutableAttributedString *actionString = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@",[model.message substringWithRange:result.range]]];
NSRange phoneRange = result.range;
NSDictionary *attribtDic = @{NSUnderlineStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
[dsc addAttributes:attribtDic range:phoneRange];
//这里需要判断是否是电话号码,并添加链接
if ([NSString isMobilePhoneOrtelePhone:actionString.string]) {
[dsc yy_setTextHighlightRange:phoneRange color:[UIColor colorWithHexString:@"#eb2323"] backgroundColor:[UIColor whiteColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
[self callPhoneThree:actionString.string];
}];
}
}];
}
label.attributedText = dsc;
}
下面是打电话方法,打电话也有很多种方式,此方法可以打完电话 返回当前应用。
- (void)callPhoneThree:(NSString *)phoneNum{
NSLog(@"拨打电话:--》%@",phoneNum);
NSString *stringNum = phoneNum;
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 getCurrentVC].view addSubview:callWebview];
}
基本结束咯,补充点就是 计算 label富文本高度咯。
为了方便,一起贴出来
#pragma mark 计算高度
- (CGFloat )calculateLabelHeightWithText:(NSString *)text lineSpace:(NSInteger )lineSpace fontName:(UIFont *)fontName size:(CGSize )size label:(UILabel *)label
{
CGFloat height = 0;
if (text.length > 0) {
// 计算内容高度,判断显示几行
NSString *firstWord = [text substringToIndex:1];
CGFloat oneRowHeight = [firstWord sizeWithAttributes:@{NSFontAttributeName:fontName}].height;
NSDictionary *attributes = @{NSFontAttributeName:fontName};
CGSize textSize = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attributes context:nil].size;
CGFloat rows = textSize.height / oneRowHeight;
if (rows == 1) {
lineSpace = 0;
height = oneRowHeight;
} else if (rows > 1) {
height = (oneRowHeight + lineSpace) * rows;
}
}
return height;
}
2019.7.8 OVER
网友评论