在开发项目中难免会遇到一个富文本,需要用到文字自适应. 下面的方法中我们可以很好的去解决这个问题
.h
@interface UILabel (HCL)
+ (CGFloat)getHeightByWidth:(CGFloat)width title:(NSString *)title font:(UIFont*)font;
+ (CGFloat)getWidthWithTitle:(NSString *)title font:(UIFont *)font;
@end
@implementation UILabel (HCL)
+ (CGFloat)getHeightByWidth:(CGFloat)width title:(NSString *)title font:(UIFont *)font
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, 0)];
label.text = title;
label.font = font;
label.numberOfLines = 0;
[label sizeToFit];
CGFloat height = label.frame.size.height;
return height;
}
+ (CGFloat)getWidthWithTitle:(NSString *)title font:(UIFont *)font {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 1000, 0)];
label.text = title;
label.font = font;
[label sizeToFit];
return label.frame.size.width;
}
@end
在使用的时候:
//标题
UILabel * titleLabel = [[UILabel alloc] init];
NSString * titleStr =@"走自己的路让别人说去吧,走自己的路让别人说去吧,走自己的路让别人说去吧";
titleLabel.text = titleStr;
//titleLabel.backgroundColor = [UIColor redColor];
titleLabel.numberOfLines = 0; ------>这句不能忘
titleLabel.lineBreakMode = NSLineBreakByCharWrapping;
titleLabel.textColor = [UIColor blackColor];
titleLabel.font = [UIFont systemFontOfSize:16.0f];------>这句字体大小要跟下面对应
[backgroundImageView addSubview:titleLabel];
[titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.mas_equalTo(self.view.mas_left).offset(40);
make.right.mas_equalTo(self.view.mas_right).offset(-40);
make.top.mas_equalTo(self.view.mas_top).offset(30);
make.height.mas_equalTo([UILabel getHeightByWidth:WIDTH-60 title:titleStr font:[UIFont systemFontOfSize:16.0f]]);------>对应
}];
希望能对大家项目中有帮助.