天天看點

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