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

你可能感兴趣的:(UIView分类一键添加点击事件clickSetAction)