------------------.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];//注意:需要设置文字颜色,否则文字会显示不太清楚
[button setImage:image forState:UIControlStateNormal];
button.space = 10;
需要特别说明的是:button和内部的imageView、titleLabel的关系:假设所用的图片尺寸是46*46的,那么当button的高度小于46的时候,imageView的高度会始终与内部图片的高度相等,当button的高度大于等于46的时候,imageView的高度始终会为46,imageView的宽度也是等同的效果;titleLabel的高度则与button的字体大小相关,默认字体18,titleLabel的默认高度为21.666667,会随着字体的增大而变高,字体的缩小而变小,titleLabel的宽度始终等同于imageView的宽度。
当然要实现图片在上面文字在下面的UIButton并不止这一种方法,我们也可以自定义一个view,在上面添加一个UIImageView和UILabel并添加一个手势来响应点击事件来实现,在这里就不提供代码了。我始终相信条条大路通罗马,解决事情的办法,不会只有一种的。所以如果您也有别的想法,请不吝赐教哦