萬盛學電腦網

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

iOS UILabel 動態高度自適應實現指南

實現「展開/收起」文本交互時,UILabel 高度需隨內容動態變化。關鍵在於 numberOfLines = 0 配合精確的尺寸計算。

核心步驟

1. 設置基本屬性

self.label.numberOfLines = 0;          // 關鍵:允許換行
self.label.lineBreakMode = NSLineBreakByWordWrapping; // 或 NSLineBreakByCharWrapping
self.label.font = [UIFont systemFontOfSize:14];

2. 計算文本佔用尺寸

- (CGSize)calculateLabelSizeForText:(NSString *)text maxWidth:(CGFloat)maxWidth {
    CGSize constraint = CGSizeMake(maxWidth, CGFLOAT_MAX);
    NSDictionary *attributes = @{NSFontAttributeName: self.label.font};
    CGRect boundingRect = [text boundingRectWithSize:constraint
                                             options:NSStringDrawingUsesLineFragmentOrigin
                                          attributes:attributes
                                             context:nil];
    return CGSizeMake(ceil(boundingRect.size.width), ceil(boundingRect.size.height));
}

注意: iOS 7+ 推薦使用 boundingRectWithSize:options:attributes:context:,舊版 sizeWithFont:constrainedToSize:lineBreakMode: 已棄用。

3. 更新 Frame 並刷新佈局

- (void)updateLabelWithText:(NSString *)text expanded:(BOOL)expanded {
    self.label.text = text;
    
    if (!expanded) {
        self.label.numberOfLines = 2; // 收起狀態限制行數
    } else {
        self.label.numberOfLines = 0; // 展開顯示全部
    }
    
    CGSize size = [self calculateLabelSizeForText:text maxWidth:self.label.frame.size.width];
    CGRect frame = self.label.frame;
    frame.size.height = size.height;
    self.label.frame = frame;
    
    // 若使用 Auto Layout,改為更新高度約束
    // self.labelHeightConstraint.constant = size.height;
    // [self.view layoutIfNeeded];
}

動畫過渡增強體驗

[UIView animateWithDuration:0.25 animations:^{
    self.labelHeightConstraint.constant = size.height;
    [self.view layoutIfNeeded];
}];

進階:帶「展開/收起」按鈕的完整交互

- (IBAction)toggleExpand:(UIButton *)sender {
    self.isExpanded = !self.isExpanded;
    [self updateLabelWithText:self.fullText expanded:self.isExpanded];
    [sender setTitle:self.isExpanded ? @"收起" : @"展開" forState:UIControlStateNormal];
}

避坑檢查清單

  • ✅ numberOfLines = 0 必須設置
  • ✅ 寬度約束固定或可計算
  • ✅ 使用 boundingRectWithSize 而非棄用 API
  • ✅ Auto Layout 環境下更新 Constraint 而非 Frame
  • ✅ 中英文混排、Emoji、特殊字符實測高度準確

掌握動態高度計算,是構建優雅閱讀體驗的基礎技能。

copyright © 萬盛學電腦網 all rights reserved