iOS控件里除了UIButton可以调节字体到左右边界的距离,其他控件都不可以,但可以自定义实现。
.h可以这样写:
// #import "InsetsLabel.h"
@interface InsetsLabel : UILabel
@property(nonatomic) UIEdgeInsets insets;
-(id) initWithFrame:(CGRect)frame andInsets: (UIEdgeInsets) insets;
-(id) initWithInsets: (UIEdgeInsets) insets;
.m可以这样写
@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
关键是重写drawTextInRect方法。
这样可以通过insets属性来调节字符距离上下左右的距离。