编程技巧 - 关联+Block

转载于: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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值