在 iOS 中計算 UILabel 高度時,若使用舊版 sizeWithFont 方法,可能在部分機型上出現高度誤差。本文說明如何在 iPhone 5s、iPhone 6 等裝置上取得較穩定的文字尺寸。
原本使用 sizeWithFont:constrainedToSize:lineBreakMode: 計算文字高度,在 iPhone 4 或 iPhone 4s 上顯示正常,但在 iPhone 5s 與 iPhone 6 真機上卻可能出現高度不足或裁切問題。
建議改用 boundingRectWithSize:options:attributes:context:,並搭配段落樣式:
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
NSDictionary *attributes = @{
NSFontAttributeName: [UIFont fontWithName:TITLE_FONT size:FONT_SIZE_FOURTEEN],
NSParagraphStyleAttributeName: paragraphStyle.copy
};
CGSize labelSize = [teacherCommentLabel.text boundingRectWithSize:CGSizeMake(180.0f, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil].size;
labelSize.height = ceil(labelSize.height);
labelSize.width = ceil(labelSize.width);
取得尺寸後,再依需求設定 Label 高度:
if (labelSize.height > BASIC_LABEL_HEIGHT) {
commentHeight = labelSize.height;
} else {
commentHeight = BASIC_LABEL_HEIGHT;
}
不同 iOS 版本對文字測量的實作可能略有差異。若專案仍需支援舊版本,可針對系統版本分別處理。此外,使用 ceil 可避免小數點造成的裁切問題。