今天项目用用到UILabel的attributedText来进行设置文本的不同显示,这个项目中使用应该会比较普遍,所以给大家分享下
主要是用官方提供的attributedText的API,下面是代码
UILabel下划线设置
_changePhoneLabel = [[UILabel alloc]init];
NSMutableAttributedString* content = [[NSMutableAttributedString alloc]initWithString:@"更换手机号"];
NSRange contentRange = {0,[content length]};
[content addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:contentRange];
_changePhoneLabel.attributedText = content;
_changePhoneLabel.textColor = C9;
_changePhoneLabel.backgroundColor = CC;
_changePhoneLabel.font = FONT14;
_changePhoneLabel.textAlignment = NSTextAlignmentCenter;
UILabel不同字体和颜色
_oldPriceLabel = [[UILabel alloc]init];
_oldPriceLabel.textAlignment = NSTextAlignmentLeft;
NSString* oldPriceStr = [NSString stringWithFormat:@"售价¥4654.00"];
NSMutableAttributedString* str = [[NSMutableAttributedString alloc]initWithString:oldPriceStr];
[str addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0x000000) range:NSMakeRange(0, 2)];
[str addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0xcc3333) range:NSMakeRange(2, 1)];
[str addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0xcc3333) range:NSMakeRange(3, str.length-5)];
[str addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0xcc3333) range:NSMakeRange(str.length-2, 2)];
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:10.0] range:NSMakeRange(str.length-2, 2)];
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:13.0] range:NSMakeRange(0, 2)];
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:11.0] range:NSMakeRange(2, 1)];
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:14.0] range:NSMakeRange(3, str.length-5)];
_oldPriceLabel.attributedText = str;
如图: