最近在項(xiàng)目中,需要有個(gè)強(qiáng)制更新功能,更新內(nèi)容,動(dòng)態(tài)顯示,系統(tǒng)的content設(shè)置,內(nèi)容是居中,丑爆了??!所以自定義個(gè)UILabel,因?yàn)樾枰袃?nèi)邊距!
UILabel不像UIButton那樣,有個(gè)contentEdgeInsets、titleEdgeInsets、imageEdgeInsets供我們?cè)O(shè)置文字或圖片與按鈕邊界的界限,所以我們只能另外想其他辦法來(lái)實(shí)現(xiàn)。其實(shí),辦法也很簡(jiǎn)單,只需要我們自定義UILabel,然后重寫drawTextInRect:方法即可實(shí)現(xiàn)我們的目標(biāo)。
如下圖

圖片發(fā)自簡(jiǎn)書App
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"發(fā)現(xiàn)新版本"
message:nil
delegate:self
cancelButtonTitle:nil
otherButtonTitles:@"立即更新", nil];
alert.tag = 3;
DGLabel *textLabel = [[DGLabel alloc] init];
textLabel.font = [UIFont systemFontOfSize:13];
textLabel.numberOfLines =0;
textLabel.textAlignment =NSTextAlignmentLeft;
textLabel.textInsets = UIEdgeInsetsMake(0.f, 10.f, 0.f, 10.f); // 設(shè)置左內(nèi)邊距
textLabel.text = responseObject[@"content"];
[alert setValue:textLabel forKey:@"accessoryView"];
[alert show];
DGLabel.h
#import <UIKit/UIKit.h>
@interface DGLabel : UILabel
@property (nonatomic, assign) UIEdgeInsets textInsets; // 控制字體與控件邊界的間隙
@end
DGLabel.m
#import "DGLabel.h"
@implementation DGLabel
- (instancetype)init {
if (self = [super init]) {
_textInsets = UIEdgeInsetsZero;
}
return self;
}
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
_textInsets = UIEdgeInsetsZero;
}
return self;
}
- (void)drawTextInRect:(CGRect)rect {
[super drawTextInRect:UIEdgeInsetsInsetRect(rect, _textInsets)];
}
@end