您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 中讓 UILabel 高度依內容自適應

編輯:iOS 開發綜合

在 iOS 中,若希望 UILabel 根據文字內容自動調整高度,核心概念是先计算文字所需尺寸,再將 Label 的高度設為計算結果。同時也必須確保 Label 的字型、寬度與換行設定一致。

1. 計算文字高度

iOS 7 之後,建議使用 boundingRectWithSize 搭配 NSAttributedString 相關屬性來計算:

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;

NSDictionary *attributes = @{
    NSFontAttributeName: ContentFont,
    NSParagraphStyleAttributeName: paragraphStyle.copy
};

CGRect frame = [strtest boundingRectWithSize:CGSizeMake(220, 1000)
                                      options:NSStringDrawingUsesLineFragmentOrigin
                                   attributes:attributes
                                      context:nil];

2. 設定 Label

建立 Label 時,必須注意以下三點:

  • Label 的 font 必須與計算時使用的 font 相同。
  • Label 的 numberOfLines 要設為 0,才能完整顯示多行文字。
  • Label 的寬度要與計算時設定的寬度一致。

3. 常見屬性

在計算文字尺寸時,常用屬性包括 NSFontAttributeName、NSParagraphStyleAttributeName、NSForegroundColorAttributeName、NSBackgroundColorAttributeName 等。若文字包含段落樣式、行距、字距或底線,都應在 attributes 中明確設定,才能讓計算結果與實際顯示一致。

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