zoukankan      html  css  js  c++  java
  • 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);
        }
    }




  • 相关阅读:
    Andio Studio
    Git常用操作汇总(转)
    1.主动学习很重要,主动学习很重要,主动学习很重要 2.官方文档 3.实践(转)
    Android应用程序的组成部分和Manifest文件(转)
    BackTrack5 (BT5)无线password破解教程之WPA/WPA2-PSK型无线password破解
    JS window.open()属性
    js产生随机数
    Node.js新手教程——怎样实现文件上传功能
    EJB究竟是什么,真的那么神奇吗??
    排序(4)---------希尔(shell)排序(C语言实现)
  • 原文地址:https://www.cnblogs.com/riskyer/p/3241155.html
Copyright © 2011-2022 走看看