IOS UILabel 一行文字实现不同颜色NSAttribut
2018-12-25 本文已影响0人
FMaarten
代码如下:
CGFloat greementX = CGRectGetMaxX(_selectBtn.frame)+CURSRCEENLENGTH(5);
UILabel *agreementLab = [[UILabel alloc] initWithFrame:CGRectMake(greementX, CURSRCEENLENGTH(10), noteView.width - greementX, CURSRCEENLENGTH(20))];
agreementLab.attributedText = [self formateAttribustring:@"我同意" colorString:@" 《苏师傅平台服务协议》"];
agreementLab.numberOfLines = 2;//最多显示多少行的属性
agreementLab.font = FONT(14);
[noteView addSubview:agreementLab];
- (NSAttributedString *)formateAttribustring:(NSString*)normalStr colorString:(NSString*)colorStr
{
//NSFontAttributeName
NSDictionary * attrsDic1 = @{NSForegroundColorAttributeName:UIColorFromHex(0x262626),NSFontAttributeName:[UIFont systemFontOfSize:14]};
NSDictionary * attrsDic2 = @{NSForegroundColorAttributeName:UIColorFromHex(0xFC4820),NSFontAttributeName:[UIFont systemFontOfSize:14]};
NSAttributedString * str1 = [[NSAttributedString alloc] initWithString:normalStr attributes:attrsDic1];
NSAttributedString * str2 = [[NSAttributedString alloc] initWithString:colorStr attributes:attrsDic2];
NSMutableAttributedString * attributeString = [[NSMutableAttributedString alloc] init];
[attributeString appendAttributedString:str1];
[attributeString appendAttributedString:str2];
return attributeString;
}
如下图所示效果 ios_label.png
注:要想实现UILabel更多不同颜色文字可在方法里面实现多个NSAttributedString拼接来达到效果