UIView+BlockGesture.m 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. //
  2. // UIView+UIView_BlockGesture.m
  3. // Created by MacKun on 15/4/25.
  4. // Copyright (c) 2015年 MacKun All rights reserved.
  5. //
  6. #import "UIView+BlockGesture.h"
  7. #import <objc/runtime.h>
  8. static char kActionHandlerTapBlockKey;
  9. static char kActionHandlerTapGestureKey;
  10. static char kActionHandlerLongPressBlockKey;
  11. static char kActionHandlerLongPressGestureKey;
  12. @implementation UIView (BlockGesture)
  13. - (void)addTapActionWithBlock:(GestureActionBlock)block
  14. {
  15. UITapGestureRecognizer *gesture = objc_getAssociatedObject(self, &kActionHandlerTapGestureKey);
  16. if (!gesture)
  17. {
  18. gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleActionForTapGesture:)];
  19. [self addGestureRecognizer:gesture];
  20. objc_setAssociatedObject(self, &kActionHandlerTapGestureKey, gesture, OBJC_ASSOCIATION_RETAIN);
  21. }
  22. objc_setAssociatedObject(self, &kActionHandlerTapBlockKey, block, OBJC_ASSOCIATION_COPY);
  23. }
  24. - (void)handleActionForTapGesture:(UITapGestureRecognizer*)gesture
  25. {
  26. if (gesture.state == UIGestureRecognizerStateRecognized)
  27. {
  28. GestureActionBlock block = objc_getAssociatedObject(self, &kActionHandlerTapBlockKey);
  29. if (block)
  30. {
  31. block(gesture);
  32. }
  33. }
  34. }
  35. - (void)addLongPressActionWithBlock:(GestureActionBlock)block
  36. {
  37. UILongPressGestureRecognizer *gesture = objc_getAssociatedObject(self, &kActionHandlerLongPressGestureKey);
  38. if (!gesture)
  39. {
  40. gesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleActionForLongPressGesture:)];
  41. [self addGestureRecognizer:gesture];
  42. objc_setAssociatedObject(self, &kActionHandlerLongPressGestureKey, gesture, OBJC_ASSOCIATION_RETAIN);
  43. }
  44. objc_setAssociatedObject(self, &kActionHandlerLongPressBlockKey, block, OBJC_ASSOCIATION_COPY);
  45. }
  46. - (void)handleActionForLongPressGesture:(UITapGestureRecognizer*)gesture
  47. {
  48. if (gesture.state == UIGestureRecognizerStateRecognized)
  49. {
  50. GestureActionBlock block = objc_getAssociatedObject(self, &kActionHandlerLongPressBlockKey);
  51. if (block)
  52. {
  53. block(gesture);
  54. }
  55. }
  56. }
  57. @end