最近做了個評論回復(fù)功能,要求用戶名變色,找了下方法,總結(jié)下

結(jié)果部分:

UILabel 中間部分文字改變顏色方法

結(jié)果部分:

UILabel *contentStr = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 300, 25)];
? ? NSString *userName=@"張三";
? ? NSString *replyUserName=@"李四";
? ? NSString *content=@"有機(jī)會看看了";
? ? NSString *string = [NSString stringWithFormat:@"%@:%@",userName,content];
? ? if (replyUserName.length != 0) {
? ? ? string = [NSString stringWithFormat:@"%@回復(fù)%@:%@",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:@"¥%@? ? 實(shí)付:%.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;