給定寬度、字體、行數限制,計算 UILabel 實際所需高度。iOS 6/7/8/9/10+ API 演進,本文對比 3 種主流方法並給出生產級封裝。
UILabel *label = [[UILabel alloc] init];
label.font = [UIFont boldSystemFontOfSize:14];
label.numberOfLines = 0; // 無行數限制
NSString *text = @"長文字內容...";
CGSize maxSize = CGSizeMake(label.frame.size.width, MAXFLOAT);
CGSize textSize = [text sizeWithFont:label.font
constrainedToSize:maxSize
lineBreakMode:NSLineBreakByWordWrapping];
// 更新 frame
label.frame = CGRectMake(label.frame.origin.x,
label.frame.origin.y,
label.frame.size.width,
textSize.height);
label.text = text;
⚠️ iOS 7 起棄用,但為相容舊專案仍可編譯運行。
UIFont *font = [UIFont fontWithName:@"HelveticaNeue" size:24];
_nameLabel.font = font;
NSDictionary *attributes = @{NSFontAttributeName: font};
CGSize size = [_nameLabel.text sizeWithAttributes:attributes];
_nameLabel.frame = CGRectMake(0, 0, size.width, size.height);
限制:不支援 `constrainedToSize` 寬度限制,**單行或已知寬度下多行需自行換行計算**。
CGFloat contentWidth = self.bounds.size.width - _contentLabel.frame.origin.x - kMargin;
UIFont *font = [UIFont fontWithName:@"HelveticaNeue" size:18];
_contentLabel.font = font;
_contentLabel.numberOfLines = 0;
_contentLabel.lineBreakMode = NSLineBreakByWordWrapping;
// 關鍵:boundingRectWithSize
CGRect textRect = [_contentLabel.text boundingRectWithSize:CGSizeMake(contentWidth, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName: font}
context:nil];
CGFloat contentHeight = textRect.size.height;
NSLog(@"調整後寬度: %.1f, 高度: %.1f", contentWidth, contentHeight);
_contentLabel.frame = CGRectMake(_contentLabel.frame.origin.x,
_contentLabel.frame.origin.y,
contentWidth, contentHeight);
關鍵參數解析:
NSStringDrawingUsesLineFragmentOrigin:按行片段佈局(多行必備)NSStringDrawingUsesFontLeading:包含行間距NSStringDrawingTruncatesLastVisibleLine:截斷最後一行加省略號CGFLOAT_MAX:高度不限制
// UILabel+AutoHeight.h
@interface UILabel (AutoHeight)
- (CGFloat)preferredHeightForWidth:(CGFloat)width;
- (void)adjustHeightForWidth:(CGFloat)width;
@end
// UILabel+AutoHeight.m
@implementation UILabel (AutoHeight)
- (CGFloat)preferredHeightForWidth:(CGFloat)width {
if (!self.text || self.text.length == 0) return 0;
if (width <= 0) return 0;
NSDictionary *attributes = @{NSFontAttributeName: self.font};
CGRect rect = [self.text boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
attributes:attributes
context:nil];
return ceil(rect.size.height);
}
- (void)adjustHeightForWidth:(CGFloat)width {
CGFloat h = [self preferredHeightForWidth:width];
CGRect frame = self.frame;
frame.size.height = h;
self.frame = frame;
}
@end
不要手動計算 frame**,讓 Auto Layout 自動解決:
// 程式碼建立約束範例
label.translatesAutoresizingMaskIntoConstraints = NO;
label.numberOfLines = 0;
[self.view addSubview:label];
[NSLayoutConstraint activateConstraints:@[
[label.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:16],
[label.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-16],
[label.topAnchor constraintEqualToAnchor:self.view.topAnchor constant:100],
// 底部約束由下方元素或 scrollView 決定
]];
// 關鍵:在 layoutSubviews 更新 preferredMaxLayoutWidth
- (void)layoutSubviews {
[super layoutSubviews];
self.label.preferredMaxLayoutWidth = self.label.bounds.size.width;
}
| 方法 | iOS 版本 | 支援多行 | 支援寬度限制 | 效能 | 推薦場景 |
|---|---|---|---|---|---|
| sizeWithFont:... | 6.0+ (棄用) | ✅ | ✅ | 中 | 舊專案維護 |
| sizeWithAttributes: | 7.0+ | ❌ (需自行換行) | ❌ | 高 | 單行、已知尺寸 |
| boundingRectWithSize: | 7.0+ | ✅ | ✅ | 中 | 通用多行計算、非Auto Layout |
| Auto Layout | 8.0+ | ✅ | ✅ (自動) | 高 (系統優化) | **現代專案首選** |