直接上代码
.h文件
#import <UIKit/UIKit.h>
@interface SXW_BUtton : UIButton
-(instancetype)initWithCoder:(NSCoder *)aDecoder;
-(instancetype)initWithFrame:(CGRect)frame;
-(CGRect)imageRectForContentRect:(CGRect)contentRect;
-(CGRect)titleRectForContentRect:(CGRect)contentRect;
@end
.m文件
#import "SXW_BUtton.h"
@interface SXW_BUtton ()
@property (nonatomic,strong) UIFont *myFont;
@end
@implementation SXW_BUtton
#pragma mark - 重写button创建方法
-(instancetype)initWithCoder:(NSCoder *)aDecoder{
if (self = [super initWithCoder:aDecoder]) {
[self setup];
}
return self;
}
-(instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
[self setup];
}
return self;
}
-(void)setup{
//设置文字字体
self.myFont = [UIFont systemFontOfSize:15.0];
self.titleLabel.font = self.myFont;
}
#pragma mark - 重写button内容布局方法
-(CGRect)imageRectForContentRect:(CGRect)contentRect{
CGFloat PADDING = 5;
//获取文字
NSString *title = self.currentTitle;
//文字高度
CGFloat titleH = [self getRectWithTitle:title].size.height;
// NSLog(@"titleH = %f", titleH);
//image的x、y、w、h
CGFloat imageH = (contentRect.size.height)/2;
CGFloat imageW = imageH;
CGFloat imageX = (contentRect.size.width - imageW) / 2;
CGFloat imageY = (contentRect.size.height - imageH - titleH - PADDING) / 2;
return CGRectMake(imageX, imageY, imageW, imageH);
}
-(CGRect)titleRectForContentRect:(CGRect)contentRect{
CGFloat PADDING = 5;
//获取文字
NSString *title = self.currentTitle;
//文字的Rect
CGRect titleRect = [self getRectWithTitle:title];
//btn的高
CGFloat btnH = contentRect.size.height;
//title的x、y、h
CGFloat titleW = titleRect.size.width;
CGFloat titleH = titleRect.size.height;
CGFloat titleX = (contentRect.size.width - titleW)/2;
CGFloat titleY = (btnH*1.5 - titleH + PADDING) / 2; //此行代码是相加减后的数学公式,不用纠结!
return CGRectMake(titleX, titleY, titleW, titleH);
}
#pragma mark - 获取文字Rect
-(CGRect)getRectWithTitle:(NSString *)title{
//NSLog(@"title = %@", title);
CGSize maxSize = CGSizeMake(MAXFLOAT, MAXFLOAT);
NSMutableDictionary *md = [NSMutableDictionary dictionary];
md[NSFontAttributeName] = self.myFont;
return [title boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:md context:nil];
}
网友评论