自定义button(标题+ 图片)
在项目中经常会用到带图片,标题的button,例如自定义的tabbar的底部按钮,返回按钮等。
系统为我们提供了一些方法来构建这样的button。
[btn setImageEdgeInsets:UIEdgeInsetsMake(5, 26, 16, 26)];
[btn setTitleEdgeInsets:UIEdgeInsetsMake(33, -26, 0, 0)];
但说实话,每次用这两个方法,里边那些数都要调整好半天,而且还要应对不同的设备,标题居中也是一个很大的问题。这里就展示一种简单的方法,克服这些问题。本人就喜欢KISS(Keep It Simple and Stupid).
下面开始:
新建WJTabbarBtn 继承自UIButton。
声明文件.h
#import <UIKit/UIKit.h>
@interface WJTabbarBtn : UIButton
{
CGRect boundingRect;/*title rect*/
}
-(instancetype)initWithFrame:(CGRect)frame
title:(NSString *)title
normalImg:(UIImage *)normalImage
selectImg:(UIImage *)selectImg;
@end
实现文件.m
#import "WJTabbarBtn.h"
# define TITLT_FONT [UIFont systemFontOfSize:12.0f] /*<标题字体大小>*/
@implementation WJTabbarBtn
/**
* 自定义初始化方法
*
* @param frame frame
*
* @return button对象
*/
- (instancetype)initWithFrame:(CGRect)frame
title:(NSString *)title
normalImg:(UIImage *)normalImage
selectImg:(UIImage *)selectImg
{
self = [super initWithFrame:frame];
if (self)
{
[self setTitle:title forState:UIControlStateNormal];
[self.titleLabel setFont:TITLT_FONT];
[self.titleLabel setTextAlignment:NSTextAlignmentCenter];
[self.titleLabel setBackgroundColor:[UIColor clearColor]];
[self setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
[self setTitleColor:[UIColor brownColor] forState:UIControlStateSelected];
[self setImage:normalImage forState:UIControlStateNormal];
[self setImage:selectImg forState:UIControlStateSelected];
//calculate title size
boundingRect=[title boundingRectWithSize:CGSizeMake(frame.size.width,20)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:TITLT_FONT}
context:nil];
}
return self;
}
/**
* 1.改变title文字的位置,构造title的矩形即可
*
* @param contentRect rect
*
* @return
*/
- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
CGFloat imageX=(self.frame.size.width - boundingRect.size.width)/2;
CGFloat imageY=contentRect.origin.y+self.imageView.bounds.size.height+2;
CGFloat width=boundingRect.size.width;
CGFloat height=boundingRect.size.height;
return CGRectMake(imageX, imageY, width, height);
}
/**
* 2.重写方法,改变 图片的位置 在 titleRect..方法后执行
*
* @param contentRect rect
*
* @return
*/
- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
CGFloat width = 30;
CGFloat imageX=(self.frame.size.width-width)/2;
CGFloat imageY=0;
CGFloat height=width;
return CGRectMake(imageX, imageY, width, height);
}
其中
- (CGRect)titleRectForContentRect:(CGRect)contentRect;
- (CGRect)imageRectForContentRect:(CGRect)contentRect;
上述两个方法是重写的系统方法。在这里可以改变button的titleLabel,imageView 的坐标,当然也可以用自动布局的形式来进行布局。这里不再写代码,有兴趣的可以改写一下。
这样就实现了常见的底部tabbar的button。