UILabel 預設會把文字鋪滿整個 bounds,四周不留空間。當你希望文字與邊框之間保留一點呼吸感(例如做成標籤或按鈕樣式),系統並沒有提供 padding 屬性。解法很簡單:繼承 UILabel,改寫 drawTextInRect:,在繪製前把矩形內縮。
#import <UIKit/UIKit.h>
@interface InsetsLabel : UILabel
@property (nonatomic) UIEdgeInsets insets;
- (id)initWithFrame:(CGRect)frame andInsets:(UIEdgeInsets)insets;
- (id)initWithInsets:(UIEdgeInsets)insets;
@end
@implementation InsetsLabel
@synthesize insets = _insets;
- (id)initWithFrame:(CGRect)frame andInsets:(UIEdgeInsets)insets {
self = [super initWithFrame:frame];
if (self) {
self.insets = insets;
}
return self;
}
- (id)initWithInsets:(UIEdgeInsets)insets {
self = [super init];
if (self) {
self.insets = insets;
}
return self;
}
// 關鍵:繪製文字前先把矩形往內縮
- (void)drawTextInRect:(CGRect)rect {
return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.insets)];
}
@end
InsetsLabel *lblTitle = [[InsetsLabel alloc] initWithFrame:CGRectMake(0, 35 + 25 * i, 185, 22)];
[lblTitle setInsets:UIEdgeInsetsMake(0, 5, 0, 5)]; // 左右各留 5pt
[self.view addSubview:lblTitle];
UIEdgeInsetsInsetRect 是 Core Graphics 提供的便利函式,會把傳入的矩形依上、左、下、右四邊各縮減指定距離。由於文字繪製仍走父類別的邏輯,只是可用區域變小了,因此換行與對齊行為都會自動跟著調整,不需要另外處理。
要注意的是,內縮只影響文字繪製範圍,並不會改變 label 本身的 frame。如果你也需要讓背景或邊框跟著留白,記得同時調整呼叫端的 frame 尺寸,或改用 sizeToFit 讓 label 依內容自動收縮。
另一個常見延伸需求是「文字不夠長時顯示省略號」。只要保留 lineBreakMode 的預設值 NSLineBreakByTruncatingTail,這個子類別就能直接支援。