首页 > 代码库 > 自定义UIButton

自定义UIButton

#import <UIKit/UIKit.h>

#import "UIView+SDExtension.h"

@interface CookButton : UIButton

 

@end

 

#import "CookButton.h"

 

@implementation CookButton

- (instancetype)initWithFrame:(CGRect)frame

{

    if (self = [super initWithFrame:frame]) {

        [self setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];

        self.titleLabel.textAlignment = NSTextAlignmentCenter;

    }

    return self;

}

//重新布局button的子视图

- (CGRect)imageRectForContentRect:(CGRect)contentRect

{

    CGFloat h = self.sd_height * 0.35;

    CGFloat w = h;

    CGFloat x = (self.sd_width - w) * 0.5;

    CGFloat y = self.sd_height * 0.2;

    return CGRectMake(x, y, w, h);

}

 

- (CGRect)titleRectForContentRect:(CGRect)contentRect

{

    return CGRectMake(0, self.sd_height * 0.6, self.sd_width, self.sd_height * 0.3);

}

 

-(void)layoutSubviews{

    [super layoutSubviews];

 

}

 

#import <UIKit/UIKit.h>

 

#define SDColorCreater(r, g, b, a) [UIColor colorWithRed:(r / 255.0) green:(g / 255.0) blue:(b / 255.0) alpha:a]

 

 

@interface UIView (SDExtension)

 

@property (nonatomic, assign) CGFloat sd_height;

@property (nonatomic, assign) CGFloat sd_width;

 

@property (nonatomic, assign) CGFloat sd_y;

@property (nonatomic, assign) CGFloat sd_x;

 

@end

 

#import "UIView+SDExtension.h"

 

@implementation UIView (SDExtension)

 

- (CGFloat)sd_height

{

    return self.frame.size.height;

}

 

- (void)setSd_height:(CGFloat)sd_height

{

    CGRect temp = self.frame;

    temp.size.height = sd_height;

    self.frame = temp;

}

 

- (CGFloat)sd_width

{

    return self.frame.size.width;

}

 

- (void)setSd_width:(CGFloat)sd_width

{

    CGRect temp = self.frame;

    temp.size.width = sd_width;

    self.frame = temp;

}

 

 

- (CGFloat)sd_y

{

    return self.frame.origin.y;

}

 

- (void)setSd_y:(CGFloat)sd_y

{

    CGRect temp = self.frame;

    temp.origin.y = sd_y;

    self.frame = temp;

}

 

- (CGFloat)sd_x

{

    return self.frame.origin.x;

}

 

- (void)setSd_x:(CGFloat)sd_x

{

    CGRect temp = self.frame;

    temp.origin.x = sd_x;

    self.frame = temp;

}

 

 

 

@end

 

自定义UIButton