UIView+gesture.m 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. //
  2. // UIView+gesture.m
  3. //
  4. // Created by CHD on 2018/5/8.
  5. // Copyright © 2018年 chd. All rights reserved.
  6. //
  7. #import "UIView+gesture.h"
  8. #import <objc/runtime.h>
  9. static char kDTActionHandlerTapBlockKey;
  10. static char kDTActionHandlerTapGestureKey;
  11. static char kDTActionHandlerLongPressBlockKey;
  12. static char kDTActionHandlerLongPressGestureKey;
  13. @implementation UIView (gesture)
  14. - (void)setTapActionWithBlock:(void (^)(UITapGestureRecognizer*tap))block
  15. {
  16. self.userInteractionEnabled = YES;
  17. UITapGestureRecognizer *gesture = objc_getAssociatedObject(self, &kDTActionHandlerTapGestureKey);
  18. if (!gesture)
  19. {
  20. gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(__handleActionForTapGesture:)];
  21. [self addGestureRecognizer:gesture];
  22. objc_setAssociatedObject(self, &kDTActionHandlerTapGestureKey, gesture, OBJC_ASSOCIATION_RETAIN);
  23. }
  24. objc_setAssociatedObject(self, &kDTActionHandlerTapBlockKey, block, OBJC_ASSOCIATION_COPY);
  25. }
  26. - (void)__handleActionForTapGesture:(UITapGestureRecognizer *)gesture
  27. {
  28. if (gesture.state == UIGestureRecognizerStateRecognized)
  29. {
  30. void(^action)(UITapGestureRecognizer*tap) = objc_getAssociatedObject(self, &kDTActionHandlerTapBlockKey);
  31. if (action)
  32. {
  33. action(gesture);
  34. }
  35. }
  36. }
  37. - (void)setLongPressActionWithBlock:(void (^)(UILongPressGestureRecognizer*longP))block
  38. {
  39. self.userInteractionEnabled = YES;
  40. UILongPressGestureRecognizer *gesture = objc_getAssociatedObject(self, &kDTActionHandlerLongPressGestureKey);
  41. if (!gesture)
  42. {
  43. gesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(__handleActionForLongPressGesture:)];
  44. [self addGestureRecognizer:gesture];
  45. objc_setAssociatedObject(self, &kDTActionHandlerLongPressGestureKey, gesture, OBJC_ASSOCIATION_RETAIN);
  46. }
  47. objc_setAssociatedObject(self, &kDTActionHandlerLongPressBlockKey, block, OBJC_ASSOCIATION_COPY);
  48. }
  49. - (void)__handleActionForLongPressGesture:(UITapGestureRecognizer *)gesture
  50. {
  51. if (gesture.state == UIGestureRecognizerStateBegan)
  52. {
  53. void(^action)(UILongPressGestureRecognizer*longP) = objc_getAssociatedObject(self, &kDTActionHandlerLongPressBlockKey);
  54. if (action)
  55. {
  56. action((UILongPressGestureRecognizer*)gesture);
  57. }
  58. }
  59. }
  60. @end