1. 程式人生 > >Label--自定義可調整內邊距的Label

Label--自定義可調整內邊距的Label

通過自定義Label實現Label的內邊距調整

自定義一個名為InsetLabel的類

InsetLabel.h檔案

#import <UIKit/UIKit.h>
@interface InsetLabel : UILabel
//用於設定Label的內邊距
@property(nonatomic) UIEdgeInsets insets;
//初始化方法一
-(id) initWithFrame:(CGRect)frame andInsets: (UIEdgeInsets) insets;
//初始化方法二
-(id) initWithInsets: (UIEdgeInsets) insets;
@end

InsetLabel.m檔案
#import "InsetLabel.h"

@implementation InsetLabel
//初始化方法一
-(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;
}
//過載drawTextInRect方法
-(void) drawTextInRect:(CGRect)rect {
    return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, self.insets)];
}
@end
建立可調整內邊距的Label
#import "ViewController.h"
#import "InsetLabel.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    InsetLabel * label=[[InsetLabel alloc] initWithFrame:CGRectMake(20, 35, 185, 22)];
    label.insets = UIEdgeInsetsMake(0, 55, 0, 5);//通過設定insets屬性直接設定Label的內邊距。
    label.text = @"測試";
    label.backgroundColor = [UIColor redColor];
    [self.view addSubview:label];
    
}


@end