NSTextCheckingResult类 ios自带识别电话号码,网址等

NSDataDetector是NSRegularExpression的子类,主要用于检测半结构化的数据:日期,地址,电话号码,正则表达式等等。
//首先有一段字符串
NSString *str = @"www.baidu.comdhfjdfj17701031767";
//根据检测的类型初始化 这里是检测电话号码和网址
NSDataDetector NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypePhoneNumber | NSTextCheckingTypeLink error:&error];
//获得检测所得到的数组
 NSArray *matches = [detector matchesInString:str options:0 range:inputRange];
//获得检测得到的总数
 //- (NSUInteger)numberOfMatchesInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range;
//第一个检测到的数据
//- (NSTextCheckingResult *)firstMatchInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range;
for (NSTextCheckingResult *match in matches) {

//当match匹配为网址时设置颜色
    if ([match resultType] == NSTextCheckingTypeLink) {
            NSRange matchRange = [match range];
          if ([self isIndex:index inRange:matchRange]) {
                [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:matchRange];
            }
           else {
                [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:matchRange];
            }
            [attributedString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:matchRange];
        }

//当match匹配为电话号码时设置其attribute
     if ([match resultType] == NSTextCheckingTypePhoneNumber) {
            NSRange matchRange = [match range];   
            if ([self isIndex:index inRange:matchRange]) {
                [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:matchRange];
            }
            else {
                [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor yellowColor] range:matchRange];
            }
            [attributedString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:matchRange];
        }
 _textLabel.attributedText = attributedString;
}

- (BOOL)isIndex:(CFIndex)index inRange:(NSRange)range

{
    return index > range.location && index < range.location+range.length;
}

 
 
 
 

转载于:https://www.cnblogs.com/MaybeQueen/p/4229053.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值