自定义Button

项目中遇到自定义按钮的问题,比较简单,记录一下,首先先展示一下效果:


新垣结衣~酱.png

自定义按钮就要重写一下两个方法:

- (CGRect)titleRectForContentRect:(CGRect)contentRect;//标题
- (CGRect)imageRectForContentRect:(CGRect)contentRect;//图片

下面我们一步一步来剖析:
1、在初始化的时候我们设置文字的大小。

-(instancetype)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super initWithCoder:aDecoder]) {
        [self setup];
    }
    return self;
}
//在调用button.frame时,会调用下面的initWithFrame方法。
-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self setup];
    }
    return self;
}

-(void)setup{
    //设置文字大小
    self.titleLabel.font = [UIFont systemFontOfSize:15.0];
}

2、对按钮初始化做一些设置。

+(instancetype)buttonWithType:(UIButtonType)buttonType{
    ZHButton *Button = [super buttonWithType:buttonType];
    if (Button) {
        Button.titleLabel.backgroundColor = [UIColor blueColor];
        Button.titleLabel.textAlignment = NSTextAlignmentCenter;
        Button.imageView.layer.masksToBounds = YES;
        
    }
    return Button;
}

3、对背景、标题以及图片做重写设置。

// 返回背景CGRect(background)
- (CGRect)backgroundRectForBounds:(CGRect)bounds{
    NSLog(@"背景:%@",NSStringFromCGRect(bounds));
    return bounds;
}

// 返回内容CGRect 标题、图片、标题与图片之间的间隔(title + image + the image and title separately)
- (CGRect)contentRectForBounds:(CGRect)bounds{
    NSLog(@"内容:%@",NSStringFromCGRect(bounds));
    return bounds;
}

// 返回标题
- (CGRect)titleRectForContentRect:(CGRect)contentRect{
    NSLog(@"标题:%@",NSStringFromCGRect(contentRect));
    return CGRectMake(0, contentRect.size.height-30, contentRect.size.width, 30);
}

// 返回图片
- (CGRect)imageRectForContentRect:(CGRect)contentRect{
    NSLog(@"图片:%@",NSStringFromCGRect(contentRect));
    CGFloat imageWidth = MIN(contentRect.size.height - 30, contentRect.size.width);
    return CGRectMake(contentRect.size.width/2 - imageWidth/2, 0, imageWidth, imageWidth);
}

Demo:https://github.com/caiqingchong/customButton

你可能感兴趣的:(自定义Button)