123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- //
- // UIView+gesture.m
- //
- // Created by CHD on 2018/5/8.
- // Copyright © 2018年 chd. All rights reserved.
- //
- #import "UIView+gesture.h"
- #import <objc/runtime.h>
- static char kActionHandlerTapBlockKey;
- static char kActionHandlerTapGestureKey;
- static char kActionHandlerLongPressBlockKey;
- static char kActionHandlerLongPressGestureKey;
- @implementation UIView (gesture)
- - (void)addTapActionWithBlock:(GestureActionBlock)block
- {
- UITapGestureRecognizer *gesture = objc_getAssociatedObject(self, &kActionHandlerTapGestureKey);
- if (!gesture)
- {
- gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleActionForTapGesture:)];
- [self addGestureRecognizer:gesture];
- objc_setAssociatedObject(self, &kActionHandlerTapGestureKey, gesture, OBJC_ASSOCIATION_RETAIN);
- }
- objc_setAssociatedObject(self, &kActionHandlerTapBlockKey, block, OBJC_ASSOCIATION_COPY);
- }
- - (void)handleActionForTapGesture:(UITapGestureRecognizer*)gesture
- {
- if (gesture.state == UIGestureRecognizerStateRecognized)
- {
- GestureActionBlock block = objc_getAssociatedObject(self, &kActionHandlerTapBlockKey);
- if (block)
- {
- block(gesture);
- }
- }
- }
- - (void)addLongPressActionWithBlock:(GestureActionBlock)block
- {
- UILongPressGestureRecognizer *gesture = objc_getAssociatedObject(self, &kActionHandlerLongPressGestureKey);
- if (!gesture)
- {
- gesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleActionForLongPressGesture:)];
- [self addGestureRecognizer:gesture];
- objc_setAssociatedObject(self, &kActionHandlerLongPressGestureKey, gesture, OBJC_ASSOCIATION_RETAIN);
- }
- objc_setAssociatedObject(self, &kActionHandlerLongPressBlockKey, block, OBJC_ASSOCIATION_COPY);
- }
- - (void)handleActionForLongPressGesture:(UITapGestureRecognizer*)gesture
- {
- if (gesture.state == UIGestureRecognizerStateRecognized)
- {
- GestureActionBlock block = objc_getAssociatedObject(self, &kActionHandlerLongPressBlockKey);
- if (block)
- {
- block(gesture);
- }
- }
- }
- @end
|