为了在同一个Label中显示两种颜色的字符,如下图(浅灰和黑色):
这里用到了NSMutableAttributedString
,它可以创建自定义属性的富文本。和它同类的还有NSAttributedString
。
要实现上面一个Label中含两种颜色字符的效果,将汉字颜色设置成浅灰色,用了下面简单的代码实现:
_followerLabel.text = @"关注 11";
NSRange followerRange = [_followerLabel.text rangeOfString:@"关注"];
NSMutableAttributedString *followerText = [[NSMutableAttributedString alloc] initWithString:_followerLabel.text];
[followerText beginEditing];
[followerText setAttributes:@{NSForegroundColorAttributeName: [UIColor colorWithRed:36.0f/255.0f green:36.0f/255.0f blue:36.0f/255.0f alpha:0.6]} range:followerRange];
[followerText endEditing];
_followerLabel.attributedText = followerText;