转载于: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来达到这种效果。
这样,可以动态增强类的功能,并且灵活使用。