相信大家都或多或少的遇到過這樣的需求,網上有很多關于實現按鈕上圖下文字的介紹,使用UIEdgeInsetsMake()來改變按鈕文字和圖片的位置的方法居多。
下面我用一種簡單粗暴的自定義按鈕方法來實現該需求。
1、新建一個類,命名為“RYButton”,繼承“UIButton”。
(1)“RYButton.h”的內容如下:
#import <UIKit/UIKit.h>
@interface RYButton : UIButton
@property (nonatomic,strong) UIImageView *topImageView;
@property (nonatomic,strong) UILabel *bottomLable;
@end
(2)“RYButton.m”的內容如下:
-(instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if(self) {
self.topImageView = [[UIImageView alloc] init];
self.topImageView.contentMode = UIViewContentModeScaleAspectFit;
[self addSubview:self.topImageView];
self.bottomLable = [[UILabel alloc] init];
self.bottomLable.textColor =[UIColor lightGrayColor];
self.bottomLable.textAlignment = NSTextAlignmentCenter; //文字居中
self.bottomLable.adjustsFontSizeToFitWidth = YES; //文字大小自適應
[self addSubview:self.bottomLable];
//給按鈕添加邊框并設置邊框的顏色
[self.layer setBorderWidth:1];
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
CGColorRef color = CGColorCreate(colorSpaceRef, (CGFloat[]){0.9,0.9,0.9,1}); //RGB and alpha
[self.layer setBorderColor:color];
}
return self;
}
-(void)layoutSubviews {
[super layoutSubviews];
//在這里面可以設置按鈕的圖片和文字的尺寸
}
2、在需要此按鈕的類添加頭文件“RYButton.h”,并創建該按鈕。
RYButton *button = [RYButton buttonWithType:UIButtonTypeCustom];
button.frame = 你要設計的按鈕的尺寸;
[self.view addSubview:button];
在創建UILabel的時候,我建議一點。我一般會創建一個類,專門用來創建各種控件,然后在需要的時候調用即可。
比如我的代碼實現
self.bottomLable = [RYKitTool createLabelTextColor:[UIColor lightGrayColor] textAlignment:NSTextAlignmentCenter];
[self addSubview:self.bottomLable];
該類方法的實現為:
+(UILabel *)createLabelTextColor:(UIColor *)textColor textAlignment:(NSTextAlignment)textAlignment {
UILabel *label = [[UILabel alloc] init];
label.textColor = textColor;
label.textAlignment = textAlignment;
label.adjustsFontSizeToFitWidth = YES;
return label;
}
這樣可以大大減少創建控件的代碼量,而且代碼重用也比較方便。