- 创建一个UIButton的类目(category)
- 需要我们重写父类中 - (void)layoutSubviews的方法
- 利用runime机制为添加的属性生产set、get方法
一 :在类目的.m文件中添加如下属性和一些常量的声明
static void *objectKeyMW = &objectKeyMW;
static void *objectKeyML = &objectKeyML;
static char const *objectKeyFrame;
@property (nonatomic ,assign) CGFloat imageViewW; // 按钮图片的大小
@property (nonatomic ,assign) CGFloat marginLeft; // 按钮图片距左边距的距离
@property (nonatomic ,assign) CGRect frameSize; // 按钮大小
二: 重写父类方法 - (void)layoutSubviews
-(void)layoutSubviews
{
[super layoutSubviews];
self.imageView.frame = CGRectMake(self.marginLeft, 0, self.imageViewW, self.imageViewW);
CGFloat centerX = self.frame.size.width / 2;
self.imageView.backgroundColor = [UIColor greenColor];
self.titleLabel.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height - self.imageViewW);
self.titleLabel.backgroundColor = [UIColor yellowColor];
self.titleLabel.center = CGPointMake(centerX, self.frame.size.height -
self.titleLabel.frame.size.height / 2);
self.titleLabel.textAlignment = NSTextAlignmentCenter;
}
三:重写init方法
- (instancetype)init
{
self = [super init];
if (self) {
self.frame = self.frameSize;
}
return self;
}
// 这个方法可以根据自己需求来自己定义只需在.h文件里声明即可
- (UIButton *)initButtonWithFrame:(CGRect)frame imageViewWidth:(CGFloat)imageViewW marginL eft:(CGFloat)marginLeft
{
self.imageViewW = imageViewW;
self.marginLeft = marginLeft;
self.frameSize = frame;
return [self init];
}
四:Runtime 生产set、get方法
- (void)setImageViewW:(CGFloat)imageViewW
{
objc_setAssociatedObject(self, objectKeyMW, @(imageViewW), OBJC_ASSOCIATION_ASSIGN);
}
- (CGFloat)imageViewW
{
return [objc_getAssociatedObject(self, objectKeyMW) floatValue];
}
- (void)setMarginLeft:(CGFloat)marginLeft
{
objc_setAssociatedObject(self, objectKeyML, @(marginLeft), OBJC_ASSOCIATION_ASSIGN);
}
- (CGFloat)marginLeft
{
return [objc_getAssociatedObject(self, objectKeyML) floatValue];
}
- (void)setFrameSize:(CGRect)frameSize
{
objc_setAssociatedObject(self, objectKeyFrame, NSStringFromCGRect(frameSize), OBJC_AS SOCIATION_RETAIN_NONATOMIC);
}
- (CGRect)frameSize
{
return CGRectFromString(objc_getAssociatedObject(self, objectKeyFrame));
}
补充:
在给一个对象添加关联对象时有五种关联策略可供选择: