UILabel
iOS 在UILabel显示不同的字体和颜色
让UILabel自适应文本长度和宽度
1. 先写文本尺寸函数
-(CGSize)getTextSize:(NSString*)str systemFont:(CGFloat)fontsize{
NSDictionary *attribute = @{NSFontAttributeName: [UIFont systemFontOfSize:fontsize]};
CGSize textSize = [str boundingRectWithSize:CGSizeMake(0, 0) options: NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
return textSize;
}
2. 写label的get方法
-(UILabel*)theaterNameLabel{
if (_theaterNameLabel==nil) {
_theaterNameLabel=[[UILabel alloc]init];
}
return _theaterNameLabel;
}
3. 写个函数调用文本尺寸函数
-(void)adjustTheaterNameLabelSize:(CGFloat)fontsize{
CGSize textSize=[self getTextSize:self.theaterNameLabel.text systemFont:fontsize];
self.theaterNameLabel.frame=CGRectMake(15, 15, textSize.width, textSize.height);
self.theaterNameLabel.font=[UIFont systemFontOfSize:fontsize];
}
在[self.view addSubview:self.theaterNameLabel];
之前调用adjustTheaterNameLabelSize
函数

这样能使显示价格的label一直在前面label后面固定的位置。
设置UILabel中有几种不同的文字属性
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:self.priceLabel.text];
[str addAttribute:NSForegroundColorAttributeName value:COLOR_RGB(219, 66, 58) range:NSMakeRange(0,str.length-2)];
[str addAttribute:NSForegroundColorAttributeName value:COLOR_RGB(153, 153, 153) range:NSMakeRange(str.length-2,2)];
[str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12.f] range:NSMakeRange(str.length-2,2)];
self.priceLabel.attributedText = str;
(代码中的COLOR_RGB是自己宏定义的)


网友评论