UILabel自动计算高度和换行
self.dizhiLabel = [[UILabel alloc]init];
self.dizhiLabel.textColor = [UIColor grayColor];
//折行
self.dizhiLabel.lineBreakMode = NSLineBreakByWordWrapping;
//必须写,否则只显示一行
[ self.dizhiLabel setNumberOfLines:0];
[self.contentView addSubview: self.dizhiLabel];
[ self.dizhiLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.zuobiaoImageView.mas_right).offset(20);
make.right.equalTo(self.contentView.mas_right).offset(-20);
make.top.equalTo( self.zuobiaoImageView.mas_top);
}];
//根据文字内容和字体计算高度
CGSize textSize = CGSizeZero;
// 多行必需使用NSStringDrawingUsesLineFragmentOrigin,网上有人说不是用NSStringDrawingUsesFontLeading计算结果不对
NSStringDrawingOptions opts = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
[style setLineBreakMode:NSLineBreakByCharWrapping];
NSDictionary *attributes = @{ NSFontAttributeName : [UIFont systemFontOfSize:17], NSParagraphStyleAttributeName : style };
CGRect rect = [ self.dizhiLabel.text boundingRectWithSize:(CGSize){ self.dizhiLabel.frame.size.width, MAXFLOAT}
options:opts
attributes:attributes
context:nil];
textSize = rect.size;
self.dizhiLabel.frame = CGRectMake(85, 15, textSize.width, textSize.height);