通过自定义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
#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