預設的 UILabel 沒有直接提供文字內邊距設定。若需要讓文字與邊界之間保留距離,可以繼承 UILabel 並自訂繪製方式。
以下範例建立一個可設定 UIEdgeInsets 的 UILabel 子類。
@interface InsetsLabel : UILabel
@property (nonatomic) UIEdgeInsets insets;
- (instancetype)initWithFrame:(CGRect)frame andInsets:(UIEdgeInsets)insets;
- (instancetype)initWithInsets:(UIEdgeInsets)insets;
@end
- (instancetype)initWithFrame:(CGRect)frame andInsets:(UIEdgeInsets)insets {
self = [super initWithFrame:frame];
if (self) {
self.insets = insets;
}
return self;
}
- (instancetype)initWithInsets:(UIEdgeInsets)insets {
self = [super init];
if (self) {
self.insets = insets;
}
return self;
}
關鍵是重載 drawTextInRect,並用 UIEdgeInsetsInsetRect 縮小實際繪製區域。
- (void)drawTextInRect:(CGRect)rect {
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.insets)];
}
這種方式很適合用於需要內距的標籤、按鈕文字或自訂卡片標題。若搭配 Auto Layout,也可以讓內距與版面約束共同運作。