UIButton之Block回调

时间:2023-03-08 16:32:00
UIButton之Block回调

本文主要介绍了两种改写UIButton的点击事件方法——继承UIButton跟给UIButton添加一个分类。附代码

方法一:继承UIButton

UIButtonBlock.h文件 如下

#import <UIKit/UIKit.h>

typedef void (^ClickActionBlock) (id obj);

@interface UIButtonBlock : UIButton

@property (nonatomic,strong)ClickActionBlock caBlock;

- (void)initWithBlock:(ClickActionBlock)clickBlock for:(UIControlEvents)event;

@end

UIButtonBlock.m文件如下:

#import "UIButtonBlock.h"

@implementation UIButtonBlock

- (void)initWithBlock:(ClickActionBlock)clickActionBlock for:(UIControlEvents)event{

[self addTarget:self action:@selector(goAction:) forControlEvents:event];

self.caBlock = clickActionBlock;

}

- (void)goAction:(UIButton *)btn{

self.caBlock(btn);

}

附使用方法。。。。。我这里是用storyboard拖出来的按钮。首先要在storyboard里的Button关联这个UIButtonBlock这个类

然后就是使用:

……

[self.clickButton initWithBlock:^(id obj) {

NSLog(@"继承之UIButton============%@",obj);

} for:UIControlEventTouchUpInside];

有同学觉得多此一举,这里不作解释。

方法二:给UIButton添加一个分类

UIButton+Block.h文件如下

#import <UIKit/UIKit.h>

typedef void (^ClickActionBlock) (id obj);

@interface UIButton (Block)

- (void)initWithBlock:(ClickActionBlock)clickBlock for:(UIControlEvents)event;

@end

UIButton+Block.m文件如下

#import "UIButton+Block.h"

#import <objc/runtime.h>

static id key;

@implementation UIButton (Block)

- (void)initWithBlock:(ClickActionBlock)clickBlock for:(UIControlEvents)event{

objc_setAssociatedObject(self, &key, clickBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);

[self addTarget:self action:@selector(goAction:) forControlEvents:event];

}

- (void)goAction:(UIButton *)sender{

ClickActionBlock block = (ClickActionBlock)objc_getAssociatedObject(self, &key);

if (block) {

block(sender);

}

}

使用方法:

……

[self.blockButton initWithBlock:^(id obj) {

NSLog(@"Runtime block============%@",obj);

} for:UIControlEventTouchUpInside ];

方法一:使用注意如果手写的UIButton需要在UIButtonBlock中再写一个初始化方法。如果是从xib拖出来的是需要关联的。

两种方法都实现了通过块来实现UIButton的addtarget方法中的@select方法的回调。代码比较粗糙大家将就着看着。