您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

可調整內邊距的 UILabel:InsetsLabel 實作

編輯:iOS 相關資訊

預設的 UILabel 沒有直接提供文字內邊距設定。若需要讓文字與邊界之間保留距離,可以繼承 UILabel 並自訂繪製方式。

建立 InsetsLabel

以下範例建立一個可設定 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,也可以讓內距與版面約束共同運作。

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