//針對(duì)普通文本設(shè)置(只要截取范圍設(shè)置)
//屬性字符串富文本
NSString *text =@"123456789熱線電話";
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, 300, 40)];
label.text= text;
label.font= [UIFont systemFontOfSize:20];
label.backgroundColor= [UIColor yellowColor];
[self.view addSubview:label];
//富文本(Rich Text Format)
//根據(jù)現(xiàn)有文本創(chuàng)建可變屬性文本
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:text];
//添加特殊的文本格式
//第一個(gè)參數(shù):屬性的名字
//第二個(gè)參數(shù):屬性的值
//第三個(gè)參數(shù):添加特殊屬性的字符串的范圍
[attrStr addAttribute:NSFontAttributeNamevalue:[UIFont systemFontOfSize:30] range:NSMakeRange(0, 9)];
// ???NSFontAttributeName改變字體大小
// ???NSForegroundColorAttributeName改變顯示的顏色(前景色)
// ???NSBackgroundColorAttributeName改變背景色
[attrStraddAttribute:NSForegroundColorAttributeNamevalue:[UIColorredColor]range:NSMakeRange(0, 9)];
[attrStr addAttribute:NSBackgroundColorAttributeNamevalue:[UIColor whiteColor] range:NSMakeRange(0, 9)];
//attributedText設(shè)置標(biāo)簽顯示的屬性字符串
label.attributedText= attrStr;
//針對(duì)特殊字符串設(shè)置(需要用正則表達(dá)式進(jìn)行查詢檢測(cè))
UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(20, 180, 300, 100)];
label2.backgroundColor= [UIColor cyanColor];
label2.font= [UIFont systemFontOfSize:20];
label2.numberOfLines= 0;
[self.view addSubview:label2];
NSString *text2 =@"這是一個(gè)微博你先更新歐冠辦公區(qū)房?jī)r(jià)方面http://www.baidu.com就本次非關(guān)系冷淡下來(lái)下面";
label2.text= text2;
//正則表達(dá)式
NSString *pattern =@"(@\\w+)|(#\\w+#)|(http(s)?://([A-Za-z0-9._-]+(/)?)*)";
//創(chuàng)建正則對(duì)象
NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
//返回的結(jié)果數(shù)組
NSArray *resultArr = [regular matchesInString:text2 options:0 range:NSMakeRange(0, text2.length)];
//創(chuàng)建可變屬性字符串
NSMutableAttributedString *attrStr2 = [[NSMutableAttributedString alloc] initWithString:text2];
//遍歷返回的結(jié)果數(shù)組
[resultArr enumerateObjectsUsingBlock:^(NSTextCheckingResult *_Nonnullobj,NSUIntegeridx,BOOL *_Nonnullstop) {
//獲取檢測(cè)到的匹配字符串的范圍
NSRange range = obj.range;
//對(duì)這個(gè)范圍內(nèi)的字符串添加屬性
[attrStr2 addAttribute:NSForegroundColorAttributeNamevalue:[UIColor redColor] range:range];
label2.attributedText = attrStr2;
}];