动态绑定。例如给控件绑定一个办法,让这个方法同时具有该控件的属性
如下面,给UIButton绑定了block,让UIButton可以通过block来回调。
#import <UIKit/UIKit.h>
typedef void (^TouchedBlock)(NSInteger tag);
@interface UIButton (Block)
-(void)addActionHandler:(TouchedBlock)touchHandler;
@end
#import "UIButton+Block.h"
#import <objc/runtime.h>
static const void *UIButtonBlockKey = &UIButtonBlockKey;
@implementation UIButton (Block)
-(void)addActionHandler:(TouchedBlock)touchHandler{
objc_setAssociatedObject(self, UIButtonBlockKey, touchHandler, OBJC_ASSOCIATION_COPY_NONATOMIC);
[self addTarget:self action:@selector(actionTouched:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)actionTouched:(UIButton *)btn{
TouchedBlock block = objc_getAssociatedObject(self, UIButtonBlockKey);
if (block) {
block(btn.tag);
}
}
直接调用
#import "UIButton+Block.h"
[button addActionHandler:^(NSInteger tag) {
NSLog(@"点击了");
}];