UIView添加支持代码块的手势

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionTap)];
    [aView addGestureRecognizer:tap];
    [tap release];

以上是很简单的给一个UIView 添加 单击手势的方法.

下面我们来改进他支持代码快


先建立一个类别

@interface UIView (XY)

-(void) addTapGestureWithTarget:(id)target action:(SEL)action;
-(void) addTapGestureWithBlock:(void(^)(void))aBlock;

-(void) removeTapGesture;

@end

代码块方法,这里要注意的是,我们得给UIView,添加一个block属性,然后在dealloc的时候释放掉.

但是在类别里重写dealloc会覆盖原本的方法,所以我们要先劫持dealloc方法

-(void) addTapGestureWithBlock:(void(^)(void))aBlock{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionTap)];
    [self addGestureRecognizer:tap];
    [tap release];
    
    objc_setAssociatedObject(self, UIView_key_tapBlock, aBlock, OBJC_ASSOCIATION_COPY);
    XY_swizzleInstanceMethod([self class], @selector(dealloc), @selector(UIView_dealloc));
}

点击的时候响应的方法

 

-(void)actionTap{
    void (^aBlock)(void) = objc_getAssociatedObject(self, UIView_key_tapBlock);
    
    if (aBlock) aBlock();
}


当UIview 被释放的时候, 清空block, 然后执行原本dealloc方法

-(void) UIView_dealloc{
    objc_removeAssociatedObjects(self);
    XY_swizzleInstanceMethod([self class], @selector(UIView_dealloc), @selector(dealloc));
[self dealloc];
}


移魂大法,

static void XY_swizzleInstanceMethod(Class c, SEL original, SEL replacement) {
    Method a = class_getInstanceMethod(c, original);
    Method b = class_getInstanceMethod(c, replacement);
    if (class_addMethod(c, original, method_getImplementation(b), method_getTypeEncoding(b)))
    {
        class_replaceMethod(c, replacement, method_getImplementation(a), method_getTypeEncoding(a));
    }
    else
    {
        method_exchangeImplementations(a, b);
    }
}




原文地址:https://www.cnblogs.com/riskyer/p/3241155.html