UILabel 是最常被使用的展示控件,但真正決定「好不好看」的往往不是它本身,而是十幾個屬性的組合方式:字體、顏色、對齊、換行、行數、自適應高度。本文把這些設置按用途歸類,並附上可直接複製的代碼。
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 = NSTextAlignmentCenter; // 水平對齊方式 label.backgroundColor = [UIColor blueColor]; // 背景顏色
label.lineBreakMode = NSLineBreakByWordWrapping; // 單詞折行方式 label.numberOfLines = 0; // 設為 0 表示不限行數,可完整顯示多行
這兩個屬性要配合使用:只把 numberOfLines 設為 0 並不會自動換行,還需要合適的 lineBreakMode。
最省事的做法是 sizeToFit:
[label sizeToFit];
如果需要更精確地控制,可以先算出文本實際佔用的尺寸,再回寫 frame:
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 NS_ENUM(NSInteger, NSLineBreakMode) {
NSLineBreakByWordWrapping = 0, // 以空格為邊界,保留整個單詞
NSLineBreakByCharWrapping, // 保留整個字符
NSLineBreakByClipping, // 到邊界為止,直接截斷
NSLineBreakByTruncatingHead, // 省略開頭,以 … 代替
NSLineBreakByTruncatingTail, // 省略結尾,以 … 代替
NSLineBreakByTruncatingMiddle // 省略中間,以 … 代替
};
各模式的實際表現差異:
使用 boundingRectWithSize:options:attributes:context: 可以同時拿到寬與高,比單純改高度更靈活:
// 初始 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) 是「允許的最大範圍」,並非固定尺寸。文本不會撐破這個框,而是在框內換行後返回真實佔用面積。
舊寫法中的 UITextAlignmentXXX、UILineBreakModeXXX、sizeWithFont: 這類 API 在後續 iOS 版本中都已更名或廢棄,新項目建議直接使用 NSTextAlignment、NSLineBreakMode 與 Text Kit 相關的測量接口。若追求更好的多語言排版(尤其是混排、字距、行距),可以改用 NSAttributedString 配合 NSParagraphStyle,能精細控制行高與段距。