首先:如果可以使用第三方的话可以看看YYKit 特别好的一个库
贴一下地址:http://www.oschina.net/p/yykit?fromerr=0QjGntqH
我的项目中是无法使用第三方的,下面是我自己用NSMutableAttributedString实现该功能的代码.
NSString *critics = [NSString stringWithString: commentModel.critics];//评论人
NSString *commentContent = [NSString stringWithString:commentModel.commentContent];//评论内容
NSString *byCritics = [NSString stringWithString:commentModel.byCritics];//被回复的人
if ([byCritics isEqualToString:@""])
{
NSString *listStr = [NSString stringWithFormat:@"%@:%@",critics,commentContent];
NSRange trueNameRange = [listStr rangeOfString:critics];
NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:listStr];
[AttributedStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20.0] range:trueNameRange];
[AttributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:trueNameRange];
self.commentLabel.attributedText = AttributedStr;
}
else
{
NSString *listStr = [NSString stringWithFormat:@"%@回复%@:%@",critics,byCritics,commentContent];
/*
一开始这样取range 并不能得到想要的结果
*/
// NSRange trueNameRange = [listStr rangeOfString:critics];
// NSRange positionRange = [listStr rangeOfString:byCritics];
NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:listStr];
[AttributedStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20.0] range:NSMakeRange(0, critics.length)];
[AttributedStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20.0] range:NSMakeRange(critics.length + 2, byCritics.length)];
[AttributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, critics.length)];
[AttributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(critics.length + 2, byCritics.length)];
self.commentLabel.attributedText = AttributedStr;
}
这样 label上显示的字符串就变成了一个有颜色的字符串.字体大小不同的字符串.当然还可以加一些别的效果.有用到的再深入研究.