NSTextCheckingResult類 ios內建識別電話號碼,網址等

來源:互聯網
上載者:User

標籤:

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內建識別電話號碼,網址等

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.