萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> iOS 開發

iOS UILabel 動態高度計算:3 種主流方法完整對比

前言:自適應高度是列表、詳情頁核心需求

給定寬度、字體、行數限制,計算 UILabel 實際所需高度。iOS 6/7/8/9/10+ API 演進,本文對比 3 種主流方法並給出生產級封裝。

方法一:sizeWithFont:constrainedToSize:lineBreakMode:(iOS 6 時代,已棄用但仍可用)


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 起棄用,但為相容舊專案仍可編譯運行。

方法二:sizeWithAttributes:(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` 寬度限制,**單行或已知寬度下多行需自行換行計算**。

方法三:boundingRectWithSize:options:attributes:context:(iOS 7+ 官方推薦,功能最完整)


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 分類


// 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

Auto Layout 時代的最佳實踐(iOS 8+)

不要手動計算 frame**,讓 Auto Layout 自動解決:

  1. 設定 `numberOfLines = 0`
  2. 設定 `preferredMaxLayoutWidth`(或在 `layoutSubviews` 更新)
  3. 加上 Leading/Trailing/Top/Bottom 約束
  4. 系統自動計算內在內容高度

// 程式碼建立約束範例
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 Layout8.0+✅✅ (自動)高 (系統優化)**現代專案首選**

常見坑點

❌ 高度計算結果為 0 或異常小
檢查:`text` 是否為 nil、字體是否設定、寬度是否 > 0、`numberOfLines` 是否為 0
❌ 中英文混排高度不準
確保 `NSStringDrawingUsesFontLeading` 選項開啟,包含行間距
❌ AttributedString 未生效
用 `attributedText` 而非 `text`,屬性字典需包含 `NSFontAttributeName`、`NSParagraphStyleAttributeName`
❌ Cell 複用時高度殘留
`prepareForReuse` 重置 frame 或依賴 Auto Layout 自動處理
copyright © 萬盛學電腦網 all rights reserved