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;}