zoukankan      html  css  js  c++  java
  • RunTime--手势应用场景(很方便)

    写一个扩展(给手势添加一个Block),给控件添加完手势之后在后面的block块中去执行手势的方法,使用起来很方便,

    首先我们创建一个类别:UIGestureRecognizer+Block

    .h

    //  Copyright © 2016年 zhiwuLiu. All rights reserved.
    //
    
    #import <UIKit/UIKit.h>
    
    typedef void(^LZWGestureBlock) (id gestureRecognizer);
    
    @interface UIGestureRecognizer (Block)
    /**
     *  使用类方法初始化添加手势
     @param block 内部 action
     使用 __unsafe_unretained __typeof(self) weakSelf = self; 防止循环引用
     */
    
    +(instancetype)lzw_ggestureRecognizerWithActionBlock:(LZWGestureBlock)block;
    
    @end

    .m

    //  Copyright © 2016年 zhiwuLiu. All rights reserved.
    //
    
    #import "UIGestureRecognizer+Block.h"
    #import <objc/runtime.h>
    
    static const int target_key;
    
    @implementation UIGestureRecognizer (Block)
    
    +(instancetype)lzw_ggestureRecognizerWithActionBlock:(LZWGestureBlock)block
    {
        return [[self alloc]initWithActionBlock:block];
    }
    
    -(instancetype)initWithActionBlock:(LZWGestureBlock)block
    {
        self = [self init];
        
        [self addActionBlock:block];
        [self addTarget:self action:@selector(invoke:)];
        
        return self;
    }
    
    
    - (void)addActionBlock:(LZWGestureBlock)block
    {
        if (block) {
            objc_setAssociatedObject(self, &target_key, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
        }
        
    }
    
    - (void)invoke:(id)sender
    {
        LZWGestureBlock block = objc_getAssociatedObject(self, &target_key);
        if (block) {
            block(sender);
        }
    }
    
    
    @end

    给控件添加手势:

    //轻拍手势
     [self.view addGestureRecognizer:[UITapGestureRecognizer lzw_ggestureRecognizerWithActionBlock:^(id gestureRecognizer) {
            
            NSLog(@"点击了view 6666 ");
            
        }]];
        
    //长按手势
        [self.view addGestureRecognizer:[UILongPressGestureRecognizer lzw_ggestureRecognizerWithActionBlock:^(id gestureRecognizer) {
            
            NSLog(@"长按-------");
            
        }]];

    使用起来是不是很方便啊...

  • 相关阅读:
    Smali语法
    css 实现垂直水平居中常用方法
    css border实现三角形
    vue-router学习笔记
    vuex状态管理
    es6 reduce的用法
    vue学习笔记
    chrome调式工具
    前端需要了解的http知识
    underscore.js and moment.js
  • 原文地址:https://www.cnblogs.com/LzwBlog/p/5892680.html
Copyright © 2011-2022 走看看