自定义button

1、何为自定义button?

  顾名思义会想到DIY,自然是系统提供的button不能够满足我的需求就需要自己DIY一个适用的button;

  比如我项目中遇到的需求:

  (这种图片在上文字在下的,系统自然不能满足,这就需要自己写一个button)

2、自定义button的思路?

  根据需求,不同之处在于button中的image和title位置的变化;所以需要重写UIButton;

  首先需要重写两个方法:

-(instancetype)initWithCoder:(NSCoder *)aDecoder;
-(instancetype)initWithFrame:(CGRect)frame;

  重写这两个方法可以确保代码创建与XIB两种方式都可实现。

  然后需要重写UIButton中的两个布局方法:

-(CGRect)imageRectForContentRect:(CGRect)contentRect;
-(CGRect)titleRectForContentRect:(CGRect)contentRect;

  以上只是大体思路,下面我会贴出具体实现的方法并作出解释;

3、自定义button的具体实现?

  既然是模仿UIbutton那么创建一个继承自UIbutton的类自不多说;

  实现代码都封装在.m文件中没必要暴漏,所以.h文件中没什么可说的;

  以下是.m文件中的具体实现:

@interface Kaka_Button ()

@property (nonatomic,strong) UIFont *myFont;

@end

@implementation Kaka_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{
    //获取文字
    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{
    //获取文字
    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];
}

  注释:获取文字Rect那个方法目的在于:button中的文字是不可以换行的,但文字长度未知所以不限制长度;但文字的高度因字号大小不同而不同,所以我们需要算出文字所占的范围来得出高度,并以此来设定image与title的大小和相对父视图的位置;

  实现后效果:

  如此达到了项目需求,(此外若遇到需求如:图在下字在上、图在右字在左的情况也自不在话下!)

原文地址:https://www.cnblogs.com/CJDog/p/5178113.html