標籤:
NSDataDetector是NSRegularExpression的子類,主要用於檢測半結構化的資料:日期,地址,電話號碼,Regex等等。
//首先有一段字串
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;
}
NSTextCheckingResult類 ios內建識別電話號碼,網址等