最近做了个评论回复功能,要求用户名变色,找了下方法,总结下
结果部分:
UILabel 中间部分文字改变颜色方法
结果部分:
UILabel *contentStr = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 300, 25)];
NSString *userName=@"张三";
NSString *replyUserName=@"李四";
NSString *content=@"有机会看看了";
NSString *string = [NSString stringWithFormat:@"%@:%@",userName,content];
if (replyUserName.length != 0) {
string = [NSString stringWithFormat:@"%@回复%@:%@",userName,replyUserName,content];
}
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:string];
[text addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:[string rangeOfString:userName]];
if (replyUserName.length != 0) {
[text addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:[string rangeOfString:replyUserName]];
}
contentStr.attributedText = text;
[self.view addSubview:contentStr];
UILabel *shifuLab = [[UILabel alloc] initWithFrame:CGRectMake(10, 200, 300, 25)];
NSString *str1 = @"¥";
long len1 = [str1 length];
NSString *shuliangStr =[NSString stringWithFormat:@"共计%d件商品",1223423];
long len2 = [shuliangStr length];
NSString *str = [NSString stringWithFormat:@"¥%@ 实付:%.2f元",shuliangStr,3434.00];
NSMutableAttributedString *str2 = [[NSMutableAttributedString alloc]initWithString:str];
[str2 addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(len1,len2)];
[str2 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15.0f] range:NSMakeRange(len1,len2)];
shifuLab.attributedText = str2;
[self.view addSubview:shifuLab];
UILabel *coverLab = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 300, 25)];
NSString *vipNumber=@"VIP会员";
NSString *coverStr=[NSString stringWithFormat:@"尊敬的用户,该视频仅限 %@ 观看",vipNumber];
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:coverStr];
[text addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:[coverStr rangeOfString:vipNumber]];
coverLab.attributedText = text;