UIView+gesture.m 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 kActionHandlerTapBlockKey;
  10. static char kActionHandlerTapGestureKey;
  11. static char kActionHandlerLongPressBlockKey;
  12. static char kActionHandlerLongPressGestureKey;
  13. @implementation UIView (gesture)
  14. - (void)addTapActionWithBlock:(GestureActionBlock)block
  15. {
  16. UITapGestureRecognizer *gesture = objc_getAssociatedObject(self, &kActionHandlerTapGestureKey);
  17. if (!gesture)
  18. {
  19. gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleActionForTapGesture:)];
  20. [self addGestureRecognizer:gesture];
  21. objc_setAssociatedObject(self, &kActionHandlerTapGestureKey, gesture, OBJC_ASSOCIATION_RETAIN);
  22. }
  23. objc_setAssociatedObject(self, &kActionHandlerTapBlockKey, block, OBJC_ASSOCIATION_COPY);
  24. }
  25. - (void)handleActionForTapGesture:(UITapGestureRecognizer*)gesture
  26. {
  27. if (gesture.state == UIGestureRecognizerStateRecognized)
  28. {
  29. GestureActionBlock block = objc_getAssociatedObject(self, &kActionHandlerTapBlockKey);
  30. if (block)
  31. {
  32. block(gesture);
  33. }
  34. }
  35. }
  36. - (void)addLongPressActionWithBlock:(GestureActionBlock)block
  37. {
  38. UILongPressGestureRecognizer *gesture = objc_getAssociatedObject(self, &kActionHandlerLongPressGestureKey);
  39. if (!gesture)
  40. {
  41. gesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleActionForLongPressGesture:)];
  42. [self addGestureRecognizer:gesture];
  43. objc_setAssociatedObject(self, &kActionHandlerLongPressGestureKey, gesture, OBJC_ASSOCIATION_RETAIN);
  44. }
  45. objc_setAssociatedObject(self, &kActionHandlerLongPressBlockKey, block, OBJC_ASSOCIATION_COPY);
  46. }
  47. - (void)handleActionForLongPressGesture:(UITapGestureRecognizer*)gesture
  48. {
  49. if (gesture.state == UIGestureRecognizerStateRecognized)
  50. {
  51. GestureActionBlock block = objc_getAssociatedObject(self, &kActionHandlerLongPressBlockKey);
  52. if (block)
  53. {
  54. block(gesture);
  55. }
  56. }
  57. }
  58. @end