码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2015-01-16 18:33:35      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:

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

 
 
 
 

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

标签:

原文地址:http://www.cnblogs.com/MaybeQueen/p/4229053.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!