ios UILabel 中部分文字變色

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


代碼部分1

結(jié)果部分:


結(jié)果部分1

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


代碼部分2

結(jié)果部分:

結(jié)果部分2

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;

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容