美文网首页
runtime的简单使用之一(动态绑定)

runtime的简单使用之一(动态绑定)

作者: seonhiu | 来源:发表于2018-04-18 10:12 被阅读6次

动态绑定。例如给控件绑定一个办法,让这个方法同时具有该控件的属性
如下面,给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(@"点击了");
}];

相关文章

网友评论

      本文标题:runtime的简单使用之一(动态绑定)

      本文链接:https://www.haomeiwen.com/subject/phxvkftx.html