您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 中依文字內容動態計算 UILabel 高度

編輯:iOS 相關資訊

一、基本做法

要讓 label 的高度隨文字自動伸縮,需要三個步驟:關閉行數限制、用 sizeWithFont 計算實際所需尺寸、再把算出來的高度套回 frame。

UILabel *label = [[UILabel alloc] init];

NSString *text = @"hellohellohellohellohellohellohellohellohellohellohellohello";
label.text = text;
label.numberOfLines = 0;          // 關鍵:0 代表不限行數

UIFont *font = [UIFont fontWithName:@"Arial" size:14];
label.font = font;

CGSize size = CGSizeMake(300, 20000.0f);   // 高度給足,讓它自由換行
size = [text sizeWithFont:font
        constrainedToSize:size
            lineBreakMode:NSLineBreakByCharWrapping];

[label setFrame:CGRectMake(10, 0, size.width, size.height)];
[self.view addSubview:label];

constrainedToSize 的第二個參數是「可用空間上限」,高度給一個夠大的值,系統就會回傳實際所需的最小尺寸。

二、lineBreakMode 的六種行為

NSLineBreakByCharWrapping:以字元為單位換行,後續內容省略不顯示。

NSLineBreakByClipping:超出寬度的部分直接裁掉,不加省略符號。

NSLineBreakByTruncatingHead:前面部分以「…」省略,顯示結尾文字。

NSLineBreakByTruncatingMiddle:中間以「…」省略,保留頭尾。

NSLineBreakByTruncatingTail:結尾以「…」省略,保留開頭(最常用)。

NSLineBreakByWordWrapping:以單字為單位換行,後續內容省略。對英文較自然,中文則不建議。

三、StoryBoard 拉出來的 label 設 frame 沒反應?

這是很典型的問題:用程式對一個在 storyboard 上拉出來的 label 呼叫 setFrame,畫面卻完全沒變。

原因是 Auto Layout 的約束優先級壓過了 frame。storyboard 上的元件預設帶有 height 約束,直接改 frame 會被約束重新計算覆蓋。解法是在 Size Inspector 中找到 Constraints 區域的 Height equals,點擊右側的齒輪圖示,選擇 Select and Edit,把 Priority 調低(例如從 1000 降為 250)。這樣一來,程式設定的 frame 就能生效,而約束只在你沒指定時才介入。

四、更推薦的現代做法

1. 用 Auto Layout 自動算高。 只要設定 label 的左右約束、以及 numberOfLines = 0,再給 table view cell 實作:

tableView.estimatedRowHeight = 44;
tableView.rowHeight = UITableViewAutomaticDimension;

系統會自動依內容計算高度,完全不需要手寫 sizeWithFont。

2. 用 sizeThatFits: 或 intrinsicContentSize。 [label sizeToFit] 會依內容調整自身尺寸,比手動算更方便。

3. sizeWithFont: 已於 iOS 7 被標記為廢棄。 請改用 boundingRectWithSize:options:attributes:context::

CGRect rect = [text boundingRectWithSize:CGSizeMake(300, CGFLOAT_MAX)
    options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
    attributes:@{NSFontAttributeName: font}
    context:nil];

新版 API 支援粗細體混排、段落樣式與行距設定,也比較能正確處理 CJK 與 emoji 的換行。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved