iOS --圖片在上面文字在下面的UIButton

------------------.h文件---------------------------

#import <UIKit/UIKit.h>

@interface MyButton : UIButton

@property (nonatomic,assign)NSInteger space;//上面的圖片與下面的文字的距離

@end

------------------.m文件---------------------------

#import "MyButton.h"

@implementation MyButton

- (void)awakeFromNib{

[super awakeFromNib];

[self setup];

}

- (void)setup{

self.titleLabel.textAlignment = NSTextAlignmentCenter;

}

- (instancetype)initWithFrame:(CGRect)frame{

self = [super initWithFrame:frame];

if (self) {

[self setup];

}

return self;

}

- (void)layoutSubviews{

[super layoutSubviews];

CGRect newframe = self.imageView.frame;

newframe.origin.x = (self.bounds.size.width - newframe.size.width)/2.0;

newframe.origin.y = 0;

newframe.size.width =? newframe.size.width;

newframe.size.height =? newframe.size.height;

self.imageView.frame = newframe;

CGRect newTitleframe = self.titleLabel.frame;

newTitleframe.origin.x =(self.bounds.size.width - newTitleframe.size.width)/2.0;

self.space = self.space>0? self.space:0;

newTitleframe.origin.y = newframe.size.height+self.space;

newTitleframe.size.width =? newframe.size.width;

newTitleframe.size.height = newTitleframe.size.height;

self.titleLabel.frame = newTitleframe;

}


---------------------具體用法----------------------------------

MyButton* button = [[MyButton alloc]init];

[self.view addSubview:button];

UIImage* image = [UIImage imageNamed:@"menu_default"];

button.frame = CGRectMake(80, 120, image.size.width, 80);

[button setTitle:@"測試" forState:UIControlStateNormal];

[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];//注意:需要設(shè)置文字顏色,否則文字會顯示不太清楚

[button setImage:image forState:UIControlStateNormal];

button.space = 10;

需要特別說明的是:button和內(nèi)部的imageView、titleLabel的關(guān)系:假設(shè)所用的圖片尺寸是46*46的,那么當button的高度小于46的時候,imageView的高度會始終與內(nèi)部圖片的高度相等,當button的高度大于等于46的時候,imageView的高度始終會為46,imageView的寬度也是等同的效果;titleLabel的高度則與button的字體大小相關(guān),默認字體18,titleLabel的默認高度為21.666667,會隨著字體的增大而變高,字體的縮小而變小,titleLabel的寬度始終等同于imageView的寬度。

當然要實現(xiàn)圖片在上面文字在下面的UIButton并不止這一種方法,我們也可以自定義一個view,在上面添加一個UIImageView和UILabel并添加一個手勢來響應(yīng)點擊事件來實現(xiàn),在這里就不提供代碼了。我始終相信條條大路通羅馬,解決事情的辦法,不會只有一種的。所以如果您也有別的想法,請不吝賜教哦

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容