为了账号安全,请及时绑定邮箱和手机立即绑定

如何把uibutton封装成block

如何把uibutton封装成block

吃鸡游戏 2019-03-12 14:08:06
如何把uibutton封装成block
查看完整描述

2 回答

?
呼啦一阵风

TA贡献1802条经验 获得超6个赞

 将UIButton的addTarget: action: forControlEvents:改造成block
建立UIButton+Block,将其引用到.pch中,#import "UIButton+Block.h"

#import <Foundation/Foundation.h>
#import <objc/runtime.h>

typedef void (^ActionBlock)();

@interface UIButton(Block)

@property (readonly) NSMutableDictionary *event;

- (void) handleControlEvent:(UIControlEvents)controlEvent withBlock:(ActionBlock)action;

@end

#import "UIButton+Block.h"

@implementation UIButton(Block)

static char overviewKey;

@dynamic event;

- (void)handleControlEvent:(UIControlEvents)event withBlock:(ActionBlock)block {
objc_setAssociatedObject(self, &overviewKey, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
[self addTarget:self action:@selector(callActionBlock:) forControlEvents:event];
}

- (void)callActionBlock:(id)sender {
ActionBlock block = (ActionBlock)objc_getAssociatedObject(self, &overviewKey);
if (block) {
block();
}
}

@end



查看完整回答
反对 回复 2019-03-20
?
牛魔王的故事

TA贡献1830条经验 获得超3个赞

将button的点击事件改为block

1、自定义一个继承于UIButton的按钮

2、声明block:

返回值类型 函数名 参数列表
typedef void (^ButtonBlock)(UIButton *);
@interface MyButton : UIButton

@property(nonatomic,copy)ButtonBlock block;
- (void)addTapBlock:(ButtonBlock)block;
@end

3、重写button的点击事件的方法
- (void)addTapBlock:(ButtonBlock)block
{
_block = block;
[self addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
}
- (void)buttonAction:(UIButton *)button
{
_block(button);
}

4、在视图控制器中调用button的block方法
[button addTapBlock:^(UIButton *button){

NSLog(@"按钮被点击了");

}];



查看完整回答
反对 回复 2019-03-20
  • 2 回答
  • 0 关注
  • 476 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信