iOS Label字体分段并显示不同颜色

2016-12-14  本文已影响249人  旅途开发者

_titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, SCREEN_WIDTH, SCREEN_HEIGHT / 14)];

_titleLabel.font = [UIFont systemFontOfSize:14];

_titleLabel.attributedText = [PublicMethod editString:titleStr CarvePlace:4 PrecedFont:14 PrecedColor:UIColorFromRGB(0x030303) BackFont:12 BackColor:UIColorFromRGB(0xb7b7b7)];

[self addSubview:_titleLabel];

//label字体分两部分的封装方法

+(NSMutableAttributedString *)editString:(NSString *)editStr CarvePlace:(int)placeNumber PrecedFont:(CGFloat)precedFont PrecedColor:(UIColor *)precedColor BackFont:(CGFloat)backFont BackColor:(UIColor *)backColor{

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:editStr];

UIFont *font1 = [UIFont systemFontOfSize:precedFont];

UIFont *font2 = [UIFont systemFontOfSize:backFont];

//设置第一部分的字体大小

[attrString addAttribute:NSFontAttributeName value:font1 range:NSMakeRange(0,placeNumber)];

//设置第一部分的字体颜色

[attrString addAttribute:NSForegroundColorAttributeName value:precedColor range:NSMakeRange(0, 4)];

//设置第二部分的字体大小

[attrString addAttribute:NSFontAttributeName value:font2 range:NSMakeRange(placeNumber,editStr.length - placeNumber)];

//设置第二部分的字体颜色

[attrString addAttribute:NSForegroundColorAttributeName value:backColor range:NSMakeRange(placeNumber,editStr.length - placeNumber)];

return attrString;

}

上一篇下一篇

猜你喜欢

热点阅读