文本在固定高宽内
+ (UILabel *)labelString:(NSString *)string andFontSize:(CGFloat)fontSize contrainWidth:(CGFloat)width constraintHeight:(CGFloat)height {
UILabel *label = [[UILabel alloc]init];
//设置label的文字
label.text = string;
//设置label文字自动换行
label.numberOfLines = 0;
//下面返回的是一个根据给定字符串、固定的宽高以及固定的文字大小计算出来的label的CGRect,并不能改变label文字的大小
NSDictionary *attribute = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]};
CGRect rect =[string boundingRectWithSize:CGSizeMake(width, height) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:attribute context:nil];
label.frame = rect;
//设置label背景色是为了测试,不需要的话可以删掉
label.backgroundColor = [UIColor lightGrayColor];
return label;
}
显示不同颜色
- (void)changeTextWithFontSize:(CGFloat)fontSize OfLabel:(UILabel *)label ToColor:(UIColor *)color withLocation:(NSInteger)loc andLength:(NSInteger)len{
NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:label.text];
//改变label某一部分字体颜色
[string addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(loc, len)];
//改变label某一部分文字大小
[string addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:fontSize] range:NSMakeRange(loc, len)];
label.attributedText = string;
}