IOS 初学 runtime 自定义Button实现按钮图片在上文字在下


  1. 创建一个UIButton的类目(category)
  2. 需要我们重写父类中 - (void)layoutSubviews的方法
  3. 利用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));

}

补充:

在给一个对象添加关联对象时有五种关联策略可供选择:

blob.png





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值