自定义Button供整个项目使用,一个项目中只用这一个Button即可

在做项目的过程中会发现经常需要自定义Button以便实现图片和文字的随意摆放,这样整个项目中就会有很多多余的类,具体的缺点我先列举几个场景。

1、一个button里面放置一个图片和一个文字,上面是图片,下面是文字,产品要求图片的尺寸必须是30*30,这时我们可以自定义一个button把图片尺寸写死。突然有一天又来了一个新的需求,图片要求40*40,又要新建一个类,突然有一天又来了一个需求,图片在下面,又要新建一个类,突然有一天又来了一个需求,图片的大小要根据屏幕的尺寸变化而变化,又新建了一个类,这样烦不烦,也许你说可以用比例来显示图片,但是如果这个产品经理就是不同意你能咋办,不是还的老老实实的写吗(程序员苦逼啊)

2、如果你是在外包,你需要在老代码上跌打开发,上一个项目新建了这么多的button,如果开发过程中不是很规范的话,文件乱放,你怎么知道该用哪一个?你怎么知道这些button的位置在哪?说实在的,这个概率在90%以上。

 

所以最好的办法是把这个button做成全局的,我全局只用这一个button,方便管理,方便迭代,新建一个button继承自uibutton,具体代码如下:

.h

#import <UIKit/UIKit.h>

@interface SKCommonButton : UIButton

- (instancetype)initWithButtonFrame:(CGRect)frame andImageFrame:(CGRect)imageFrame andTitleFrame:(CGRect)titleFrame;
@end


.m

#import "SKCommonButton.h"

@interface SKCommonButton()

/**图片的尺寸*/
@property (nonatomic,assign) CGRect imageFame;

/**图片的尺寸*/
@property (nonatomic,assign) CGRect titleFame;

@end

@implementation SKCommonButton

- (instancetype)initWithButtonFrame:(CGRect)frame andImageFrame:(CGRect)imageFrame andTitleFrame:(CGRect)titleFrame
{
    if (self == [super initWithFrame:frame]) {
        //设置图片居中
        self.imageView.contentMode = UIViewContentModeScaleAspectFit;
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        self.titleLabel.font = [UIFont systemFontOfSize:15];
        [self setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
        
        self.imageFame = imageFrame;
        self.titleFame = titleFrame;
    }
    return self;
}

- (void)setHighlighted:(BOOL)highlighted
{}

/*覆盖父类的方法,设置button的文字位置*/
- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
    
    return self.titleFame;
}

- (CGRect)imageRectForContentRect:(CGRect)contentRect
{

    return self.imageFame;
}

使用方法:在你创建的时候,根据实际情况自己去设置图片和文字的位置。

 

 

移动端热门技术交流群170229489

 

posted @ 2016-09-14 15:34  Darren-chen  阅读(258)  评论(0编辑  收藏  举报