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);
        }
    }




  • 相关阅读:
    第三方接口开发规范
    项目经理、技术经理、team leader
    ibatis #和$符号的区别,传入字符串而不加引号
    WindowManager.LayoutParams详解
    AIDL 编译报can be an out parameter, so you must declare it as in, out or inout原因探究
    map里的keyset()和entryset()方法.
    android 使用代码实现 RelativeLayout布局
    Android中的Selector
    intentfilter 之 data 「scheme, host, port, mimeType, path, pathPrefix, pathPattern」
    找信息的方法
  • 原文地址:https://www.cnblogs.com/riskyer/p/3241155.html
Copyright © 2011-2022 走看看