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(@"长按-------");
        
    }]];

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

posted on 2016-09-21 15:05  刘志武  阅读(168)  评论(0编辑  收藏  举报

导航