------------------.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),在這里就不提供代碼了。我始終相信條條大路通羅馬,解決事情的辦法,不會只有一種的。所以如果您也有別的想法,請不吝賜教哦