搜索
您的当前位置:首页正文

富文本设置标签

来源:二三娱乐

//针对普通文本设置(只要截取范围设置)

//属性字符串富文本

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)

//根据现有文本创建可变属性文本

NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:text];

//添加特殊的文本格式

//第一个参数:属性的名字

//第二个参数:属性的值

//第三个参数:添加特殊属性的字符串的范围

[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设置标签显示的属性字符串

label.attributedText= attrStr;

//针对特殊字符串设置(需要用正则表达式进行查询检测)

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

label2.text= text2;

//正则表达式

//创建正则对象

NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];

//返回的结果数组

NSArray *resultArr = [regular matchesInString:text2 options:0 range:NSMakeRange(0, text2.length)];

//创建可变属性字符串

NSMutableAttributedString *attrStr2 = [[NSMutableAttributedString alloc] initWithString:text2];

//遍历返回的结果数组

[resultArr enumerateObjectsUsingBlock:^(NSTextCheckingResult *_Nonnullobj,NSUIntegeridx,BOOL *_Nonnullstop) {

//获取检测到的匹配字符串的范围

NSRange range = obj.range;

//对这个范围内的字符串添加属性

[attrStr2 addAttribute:NSForegroundColorAttributeNamevalue:[UIColor redColor] range:range];

label2.attributedText = attrStr2;

}];

Top