UIButton在開發(fā)中經(jīng)常使用,默認(rèn)布局是左image右title,實(shí)際開發(fā)中常常需要上image下title,顯然默認(rèn)的樣式不能滿足我們的需求。之前我使用titleEdgeInsets和imageEdgeInsets去調(diào)整,如下:
CGFloat w = [UIScreen mainScreen].bounds.size.width /4;
[but setImageEdgeInsets:UIEdgeInsetsMake(0, w / 3, 30, w / 3)];
[but setTitleEdgeInsets:UIEdgeInsetsMake(50, -image.size.width, 0, 0)];
感覺很不爽,每個(gè)button都需要重復(fù)的代碼,敲的真很心累!
一直以來總想找到一個(gè)比較懶的方法,一次封裝,永久調(diào)用。功夫不負(fù)有心人,今天總算找到了一個(gè)API,可以實(shí)現(xiàn),竊喜。
- (instancetype)initWithFrame:(CGRect)frame
- (CGRect)imageRectForContentRect:(CGRect)contentRect
我們需要自己寫一個(gè)類,繼承于UIButton。 由于是上圖片下文字結(jié)構(gòu)的布局,故命名為HTVerticalButton,在HTVerticalButton.m文件中直接改寫UIButton的方法,如下:
- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
CGFloat titleY = contentRect.size.height *0.6;
CGFloat titleW = contentRect.size.width;
CGFloat titleH = contentRect.size.height - titleY;
return CGRectMake(0, titleY , titleW, titleH);
}
- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
CGFloat imageW = CGRectGetWidth(contentRect);
CGFloat imageH = contentRect.size.height * 0.6;
return CGRectMake(0, 0, imageW, imageH);
}
發(fā)現(xiàn)基本上實(shí)現(xiàn)了我們的需求,唯有文字沒有居中對齊,故還需要設(shè)置文字的居中對齊方式,本著只想一次修改的目的,我還是在HTVerticalButton.m中設(shè)置。
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
self.titleLabel.textAlignment = NSTextAlignmentCenter;
}
return self;
}
運(yùn)行下,基本解決了我們的需求。
使用時(shí)只需要導(dǎo)入我們自定義的類#import "HTVerticalButton.h"即可
- (void)setupUI
{
CGFloat w = self.bounds.size.width / 5;
CGFloat h = self.bounds.size.height / 2;
for (int i = 0; i<10; i++)
{
HTVerticalButton *but =[HTVerticalButton buttonWithType:UIButtonTypeCustom];
but.frame = CGRectMake(i%5 * w, i/5 * h, w, h);
[but setTitle:@"按鈕" forState:UIControlStateNormal];
[but setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[but setImage:[UIImage imageNamed:@"shape-127"] forState:UIControlStateNormal];
but.backgroundColor = [UIColor redColor];
but.layer.masksToBounds = YES;
but.layer.cornerRadius = 5;
[self addSubview:but];
}
}
這樣就像使用系統(tǒng)UIButton方法樣,直接設(shè)置title和image后,再也不需要設(shè)置EdgeInsets,不用去關(guān)心布局問題了。
HTVerticalButton.png
注意下:
- 如果需要重寫系統(tǒng)的方法,可以自己寫個(gè)類繼承系統(tǒng)類,然后在.m文件中直接寫你的實(shí)現(xiàn),無需在.h文件中再次聲明此方法。
- 重寫系統(tǒng)方法時(shí),不可以使用類別,會(huì)報(bào)警告的。