UILabel 文字自適應(yīng)高度
- 原理: 因為在 ArticleView 對應(yīng)的 xib 文件中,設(shè)置了其他控件的自動布局, 但是當(dāng) ArticleView 創(chuàng)建的 view 對象添加到 contentLabel 的時候, 卻因為 view 與 contentLabel 沒有自動布局約束, 導(dǎo)致 view 中的布局不能生效.
- 解決思路:
- 1.通過設(shè)置 view 的 frame 相應(yīng)的值, 設(shè)置 frame 的值,強行將 view 的內(nèi)容壓縮在 frame 的高度中.
- 2 將缺少的 view 與 contentView 的自動布局加上, 達(dá)到自動布局生效的效果.
解決方法:
- 使用 [label sizeThatFits:] 方法
// contentSize 保存的是根據(jù) contentView 的寬度, 不限制的高度, 創(chuàng)建的一個 size 對象
CGSize contentSize = CGSizeMake(CGRectGetWidth(self.contentView.frame), CGFLOAT_MAX);
// view.contentLabel 中已經(jīng)設(shè)置了文字, 使用 sizeThatFits 方法求出一個 CGSize 值, 取出其中的 height.
CGFloat contentHeight = [view.contentLabel sizeThatFits:contentSize].height;
- 使用 [NSString boundingRectWithSize: options: attributes: context:] 方法
CGFloat contentHeight = [view.contentLabel.text boundingRectWithSize:CGSizeMake(CGRectGetWidth(self.contentView.bounds) - 46.f, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:view.contentLabel.font}
context:nil].size.height;
- 使用 [label systemLayoutSizeFittingSize:] 方法
// 先設(shè)置 contentLabel 能顯示的最大寬度
view.contentLabel.preferredMaxLayoutWidth = CGRectGetWidth(self.contentView.bounds) - 46;
// 獲取 label 對最大寬度的適應(yīng) size, 取出 height 值
// UILayoutFittingCompressedSize 在 label 的內(nèi)容限制中最小化 label 高度
// UILayoutFittingExpandedSize 在壓縮范圍內(nèi)最大化 label 的高度
CGFloat contentHeight = [view.contentLabel systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
CGRect frame = CGRectMake(0, CGRectGetMaxY([self.contentView.subviews lastObject].frame)+12, CGRectGetWidth(self.contentView.frame), contentHeight+39);
[view setFrame:frame];
// 關(guān)閉 view 和 contentView 自帶的 AutoresizingMask
[view setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.contentView setTranslatesAutoresizingMaskIntoConstraints:NO];
// 這里 [self.contentView.subviews lastObject] 代表的是已經(jīng)添加到 contentView 中的視圖
// view 表示還為添加到 contentView 中的視圖
CGFloat topConstraintY = CGRectGetMaxY([self.contentView.subviews lastObject].frame);
[self.contentView addSubview:view];
NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self.contentView
attribute:NSLayoutAttributeTop
multiplier:1
constant:topConstraintY + 12];
NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:self.contentView
attribute:NSLayoutAttributeLeft
multiplier:1
constant:10];
NSLayoutConstraint *rightConstraint = [NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeRight
relatedBy:NSLayoutRelationEqual
toItem:self.contentView
attribute:NSLayoutAttributeRight
multiplier:1
constant:-10];
[self.contentView addConstraints:[NSArray arrayWithObjects:topConstraint, leftConstraint, rightConstraint, nil]];
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者