UIButton的点击事件使用block回调

2017-02-22  本文已影响63人  西门丨不吹雪

直接上代码

.h文件
#import <UIKit/UIKit.h>
typedef void (^btnBlock)();

@interfce UIButton (Block)

- (void)handelWithBlock:(btnBlock)block;

@end

.m文件

#import "UIButton+Block.h"
#import <objc/runtime.h>

static const char btnKey;

@implementation UIButton (Block)

- (void)handelWithBlock:(btnBlock)block
{
    if (block)
    {
       set方法将self和block通过btnkey关联起来
        objc_setAssociatedObject(self, &btnKey, block, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }

    [self addTarget:self action:@selector(btnAction) forControlEvents:UIControlEventTouchUpInside];
}

- (void)btnAction
{
     get方法通过key获取对象
    btnBlock block = objc_getAssociatedObject(self, &btnKey);
    block();
}

@end

tips: 使用objc_setAssociatedObject,需要引入头文件 #import <objc/runtime.h>

上一篇下一篇

猜你喜欢

热点阅读