UILabel+Extension.h
@interface UILabel (Calculate)
//根据宽度求高度 content 计算的内容 width 计算的宽度 font字体大小
+ (CGFloat)getLabelHeightWithText:(NSString *)text
width:(CGFloat)width
font: (CGFloat)font;
//根据高度度求宽度 text 计算的内容 Height 计算的高度 font字体大小
+ (CGFloat)getLabelWidthWithText:(NSString *)text
height:(CGFloat)height
font:(CGFloat)font;
@end
UILabel+Extension.m文件
@implementation UILabel (Calculate)
//根据宽度求高度 content 计算的内容 width 计算的宽度 font字体大小
+ (CGFloat)getLabelHeightWithText:(NSString *)text
width:(CGFloat)width
font:(CGFloat)font
{
CGRect rect = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]}
context:nil];
return rect.size.height;
}
//根据高度度求宽度 text 计算的内容 Height 计算的高度 font字体大小
+ (CGFloat)getLabelWidthWithText:(NSString *)text
height:(CGFloat)height
font:(CGFloat)font
{
CGRect rect = [text boundingRectWithSize:CGSizeMake(MAXFLOAT, height)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]}
context:nil];
return rect.size.width;
}
@end
使用UILabel+Extension.h
UIView *bgView = [[UIView alloc] init];
[bgView mas_makeConstraints:^(MASConstraintMaker *make) {
//make.width.mas_equalTo(200);
make.height.mas_equalTo(20);
make.top.mas_equalTo(bottomLine.mas_bottom).offset(40);
}];
[bgView layoutIfNeeded];
CGFloat readLabWidth = [UILabel getLabelWidthWithText:readLab.text height:20 font:14];
CGFloat protocolBtnWidth = [UILabel getLabelWidthWithText:[protocolBtn titleForState:UIControlStateNormal] height:20 font:14.0];
CGFloat bgViewWidth = readLabWidth + protocolBtnWidth;
[bgView mas_updateConstraints:^(MASConstraintMaker *make) {
make.width.mas_equalTo(bgViewWidth);
make.centerX.mas_equalTo(bottomLine);
}];