您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

自製可設定內距的 InsetsLabel

編輯:iOS 開發綜合

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,這個子類別就能直接支援。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved