今天在 iOS14 上遇到了 UILabel 高度異常的問題,具體的表現(xiàn)是:系統(tǒng)可能認(rèn)為文本太多換行了,于是高度約束的值多了一行的高度。如圖

錯(cuò)誤的高度約束
文本確實(shí)沒換行,但正確的情況應(yīng)該是,Label 寬度明顯是足夠的,不應(yīng)該多算一行高度。
當(dāng)我減少一些字符,小于一個(gè)最大臨界值時(shí),高度就計(jì)算正常了,比如(刪掉了一個(gè)字符)

文字少高度才正確
具體原因也不想去分析了,解決辦法就是自己計(jì)算高度,自己修改高度約束
@interface TightLabel : UILabel
@end
@implementation TightLabel
- (void)layoutSubviews {
[super layoutSubviews];
[self.constraints enumerateObjectsUsingBlock:^(NSLayoutConstraint *obj, NSUInteger idx, BOOL *stop) {
if (obj.firstItem == self && obj.firstAttribute == NSLayoutAttributeHeight) {
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
style.lineBreakMode = self.lineBreakMode;
style.alignment = self.textAlignment;
CGRect bounds = [self.text boundingRectWithSize:CGSizeMake(CGRectGetWidth(self.bounds), CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
attributes:@{ NSFontAttributeName: self.font, NSParagraphStyleAttributeName: style } context:nil];
obj.constant = ceil(bounds.size.height) + 1;
*stop = YES;
}
}];
}
@end
使用自定義的 TightLabel 替代系統(tǒng)的類,高度就不會(huì)有問題了