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

iOS 7 中動態計算 UILabel 的高度

編輯:iOS 開發綜合

當 UILabel 的文字長度不固定時,往往需要動態計算它的高度。以下透過一個 UILabel 的分類(Category)來達成,並附上具體使用範例。

一、標頭檔

#import <UIKit/UIKit.h>

@interface UILabel (ContentSize)
- (CGSize)contentSize;
@end

二、實作檔

#import "UILabel+ContentSize.h"

@implementation UILabel (ContentSize)

- (CGSize)contentSize {
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = self.lineBreakMode;
    paragraphStyle.alignment = self.textAlignment;
    NSDictionary *attributes = @{NSFontAttributeName : self.font,
                                 NSParagraphStyleAttributeName : paragraphStyle};
    CGSize contentSize = [self.text boundingRectWithSize:CGSizeMake(self.frame.size.width, MAXFLOAT)
                                                options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
                                             attributes:attributes
                                                context:nil].size;
    return contentSize;
}

@end

三、具體使用

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, 280, 20)];
label.font = [UIFont boldSystemFontOfSize:15.0f];   // 字型大小
label.numberOfLines = 0;                            // 必須設定此屬性,否則 UILabel 不會換行
label.textColor = [UIColor whiteColor];
label.textAlignment = NSTextAlignmentLeft;          // 對齊方式
[label setBackgroundColor:[UIColor redColor]];
label.lineBreakMode = NSLineBreakByWordWrapping;

NSString *str = @"這裡放入需要顯示的長文字內容……";

// 舊方法:用 sizeWithFont:constrainedToSize:lineBreakMode: 計算,再重設 frame
// CGSize size = [str sizeWithFont:label.font constrainedToSize:CGSizeMake(label.frame.size.width, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
// [label setFrame:CGRectMake(20, 10, 280, size.height)];

label.text = str;
// 寬度不變,依文字多寡計算高度
[label setFrame:CGRectMake(20, 20, 280, [label contentSize].height)];
[self.view addSubview:label];

這裡有幾點要特別注意:

1、在呼叫 contentSize 之前,要先設定 label.lineBreakMode 屬性。

2、文字是否換行的關鍵在於 CGSizeMake(w, h) 的設定,差異主要就在 w、h 的數值。

相較於舊的 sizeWithFont 方法,用 boundingRectWithSize:options:attributes:context: 能更準確地計算出文字在指定寬度下所需的高度。

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