编程技巧 - 关联+Block

来源:互联网 发布:linux net snmp使用 编辑:程序博客网 时间:2024/06/05 09:04

转载于:http://www.cocoachina.com/ios/20141105/10134.html

#pragma mark - LBRuntimeView.@interface LBRuntimeView : UIView- (void)setTapActionWithBlock:(void(^)(void))block;@end

实现:

#pragma mark - LBRuntimeView.static char kDTActionHandlerTapGestureKey;@interface LBRuntimeView ()@end@implementation LBRuntimeView- (void)setTapActionWithBlock:(void(^)(void))block{        UITapGestureRecognizer *gesture = objc_getAssociatedObject(self, &kDTActionHandlerTapGestureKey);        if (!gesture) {        gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(__handleActionForTapGesture:)];        [self addGestureRecognizer:gesture];        objc_setAssociatedObject(self, &kDTActionHandlerTapGestureKey, gesture, OBJC_ASSOCIATION_RETAIN);    }        objc_setAssociatedObject(self, &kDTActionHandlerTapGestureKey, block, OBJC_ASSOCIATION_COPY);}// 这样的结构超帅的哦,static char是一个全局的// 这样才能起到连结的作用嘛- (void)__handleActionForTapGesture:(UITapGestureRecognizer *)gesture{    if (gesture.state == UIGestureRecognizerStateEnded) {                void(^action)(void) = objc_getAssociatedObject(self, &kDTActionHandlerTapGestureKey);                if (action) {                        action();        }    }}@end


调用:

    __weak LBRuntimeView *blockView = runtimeView;        [runtimeView setTapActionWithBlock:^{            [blockView setBackgroundColor: [UIColor colorWithRed:arc4random_uniform(255)/255.0 green:arc4random_uniform(255)/255.0 blue:arc4random_uniform(255)/255.0 alpha:1]];        }];


几乎所有的类结构都可以这样 关联 + block来达到这种效果。


这样,可以动态增强类的功能,并且灵活使用。


0 0