UILabel 是最樸素也最高頻的 iOS 元件,但要把文字排得漂亮,牽涉到的屬性其實不少:字型、顏色、對齊、換行策略,以及最麻煩的「高度自適應」。本文把這些常用設定整理成一份可查閱的清單。
// 建立物件 UILabel *label = [[UILabel alloc] initWithFrame:self.view.bounds]; // 顯示文字 label.text = @"This is a UILabel Demo,"; // 字型 label.font = [UIFont fontWithName:@"Arial" size:35]; // 文字顏色 label.textColor = [UIColor yellowColor]; // 水平對齊位置 label.textAlignment = UITextAlignmentCenter; // 背景顏色 label.backgroundColor = [UIColor blueColor];
預設情況下 UILabel 只顯示一行,超出部分會被截掉。想顯示多行,把 numberOfLines 設為 0 即可(0 代表不限制行數):
// 單字折行方式 label.lineBreakMode = UILineBreakModeWordWrap; // 0 代表不限行數,也就是允許完整多行顯示 label.numberOfLines = 0;
最省事的做法是直接呼叫 sizeToFit,讓 label 依內容自行決定尺寸:
[label sizeToFit];
若你只想改高度、保留寬度(例如配合固定寬度的排版),則需要先量出文字的實際尺寸:
CGSize size = [label.text sizeWithFont:label.font
constrainedToSize:self.view.bounds.size
lineBreakMode:label.lineBreakMode];
CGRect rect = label.frame;
rect.size.height = size.height;
label.frame = rect;
這個列舉決定了「換行時怎麼斷」以及「斷不下時怎麼省略」,是文字排版的核心:
typedef enum {
UILineBreakModeWordWrap = 0, // 以空白為界,保留整個單詞
UILineBreakModeCharacterWrap, // 保留整個字元
UILineBreakModeClip, // 到邊界為止,直接切斷
UILineBreakModeHeadTruncation, // 省略開頭,以……代替
UILineBreakModeTailTruncation, // 省略結尾,以……代替
UILineBreakModeMiddleTruncation, // 省略中間,以……代替,多行時作用於最後一行
} UILineBreakMode;
逐項對照實際行為:
先給一個臨時 frame,再用 boundingRectWithSize:options:attributes:context: 精準算出文字佔用的矩形,最後回寫 frame:
// 這個 frame 只是初始值,後面會重新計算 size
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
label.numberOfLines = 0;
label.backgroundColor = [UIColor clearColor];
NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:20]};
NSString *str = @"abcdefg你上課可是你的拿到了";
CGSize textSize = [str boundingRectWithSize:CGSizeMake(100, 100)
options:NSStringDrawingTruncatesLastVisibleLine
attributes:attributes
context:nil].size;
[label setFrame:CGRectMake(100, 100, textSize.width, textSize.height)];
label.textColor = [UIColor greenColor];
label.text = str;
[self.view addSubview:label];
這裡的 CGSizeMake(100, 100) 是「允許的最大範圍」,計算結果會落在這個範圍內的最小合適矩形。実務上這個寫法比 sizeToFit 更可控,特別適合需要精算版面高度、進而決定父容器高度的場合。