2013年3月20日 星期三

修改unbutton, 加入 block

轉貼自 http://www.cocoachina.com/bbs/simple/?t133158.html

使用 Category 方法建立比 subclass 方法好多了

#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

進階 https://gist.github.com/joshdholtz/2468899

沒有留言: