主要思路是通過調用UILabel
的- (CGSize)sizeThatFits:(CGSize)size
方法來得到label的自適應高度值。
注意這裏不能調用NSString
的- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode
方法來獲得高度,因爲如果未來label的可以配置其他行間距,自定義字體等等,那麼此方法便會失效。 其實,iOS的UILabel已經可以支持不同的字體屬性,比如大小,顏色。所以此方法已經不再是正確的了
1.針對非AutoLayout的情況,直接調整frame:
- (void)autoHeightOfLabel:(UILabel *)label{
//Calculate the expected size based on the font and linebreak mode of your label
// FLT_MAX here simply means no constraint in height
CGSize maximumLabelSize = CGSizeMake(label.frame.size.width, FLT_MAX);
CGSize expectedLabelSize = [label sizeThatFits:maximumLabelSize];
//adjust the label the the new height.
CGRect newFrame = label.frame;
newFrame.size.height = expectedLabelSize.height;
label.frame = newFrame;
[label updateConstraintsIfNeeded];
}
2.針對AutoLayout的情況,需要更新約束:
- (void)autoHeightOfLabel:(UILabel *)label{
//Calculate the expected size based on the font and linebreak mode of your label
// FLT_MAX here simply means no constraint in height
CGSize maximumLabelSize = CGSizeMake(label.frame.size.width, FLT_MAX);
//add the new height constraint to the label
for (NSLayoutConstraint *constraint in label.constraints) {
if (constraint.firstItem == label && constraint.firstAttribute == NSLayoutAttributeHeight && constraint.secondItem == nil) {
constraint.constant = expectedLabelSize.height;
break;
}
}
}