美文网首页
NSTextCheckingResult类 ios自带识别电话号

NSTextCheckingResult类 ios自带识别电话号

作者: __May__ | 来源:发表于2018-06-08 16:26 被阅读0次

    NSDataDetector是NSRegularExpression的子类,主要用于检测半结构化的数据:日期,地址,电话号码,正则表达式等等。

    //首先有一段字符串

    NSString *str = @"www.baidu.comdhfjdfj17701031767";

    //根据检测的类型初始化 这里是检测电话号码和网址

    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匹配为网址时设置颜色

            NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];

            if ([match resultType] == NSTextCheckingTypeLink) {

                NSRange matchRange = [match range];            //这里可以自行设置

                [attributedStringaddAttribute:NSForegroundColorAttributeName value:[UIColor yellowColor] range:matchRange];

                [attributedStringaddAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:matchRange];

            }

            //当match匹配为电话号码时设置其attribute

            if ([match resultType] == NSTextCheckingTypePhoneNumber) {

                NSRange matchRange = [match range];

                //这里可以自行设置

                [attributedStringaddAttribute:NSForegroundColorAttributeName value:[UIColor yellowColor] range:matchRange];

                [attributedStringaddAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:matchRange];

            }

        }

        //设置label的内容

        //textLabel.attributedText = attributedString;

    相关文章

      网友评论

          本文标题:NSTextCheckingResult类 ios自带识别电话号

          本文链接:https://www.haomeiwen.com/subject/eeuasftx.html