UIView分类一键添加点击事件clickSetAction

#import "UIView+Gesture.h"

static const NSString *clickSetActionKey = @"clickSetActionKey";

static const NSString *tapGestureKey = @"tapGestureKey";

@implementation UIView (Gesture)

- (void)clickSetAction:(ActionBlock)block{

    if(block !=nil) {

        objc_setAssociatedObject(self, &clickSetActionKey, block, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

        self.userInteractionEnabled = YES;

        UITapGestureRecognizer*oldGesture = [selftapGesture];

        if( oldGesture !=nil) {

            [selfremoveGestureRecognizer:oldGesture];

        }

        UITapGestureRecognizer*newGesture = [[UITapGestureRecognizeralloc]initWithTarget:selfaction:@selector(blockHandleAction:)];

        [selfsetTapGesture:newGesture];

        [selfaddGestureRecognizer:newGesture];

    }else{

        objc_setAssociatedObject(self, &clickSetActionKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

        UITapGestureRecognizer*oldGesture = [selftapGesture];

        if( oldGesture !=nil) {

            [selfremoveGestureRecognizer:oldGesture];

        }

    }

}

#pragma mark - Private Func

- (void)setTapGesture:(UITapGestureRecognizer *)tap{

    if(tap !=nil){

        objc_setAssociatedObject(self, &tapGestureKey, tap, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

    }else{

        objc_setAssociatedObject(self, &tapGestureKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

    }

}

- (UITapGestureRecognizer *)tapGesture{

    return objc_getAssociatedObject(self, &tapGestureKey);

}

- (void)blockHandleAction:(UIGestureRecognizer *)sender{

    ActionBlockblock =  objc_getAssociatedObject(self, &clickSetActionKey);

    if(block !=nil) {

        block();

    }

}

@end

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容