UIGestureRecognizer+YYAdd.m 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. //
  2. // UIGestureRecognizer+YYAdd.m
  3. // YYKit <https://github.com/ibireme/YYKit>
  4. //
  5. // Created by ibireme on 13/10/13.
  6. // Copyright (c) 2015 ibireme.
  7. //
  8. // This source code is licensed under the MIT-style license found in the
  9. // LICENSE file in the root directory of this source tree.
  10. //
  11. #import "UIGestureRecognizer+YYAdd.h"
  12. #import "YYKitMacro.h"
  13. #import <objc/runtime.h>
  14. static const int block_key;
  15. @interface _YYUIGestureRecognizerBlockTarget : NSObject
  16. @property (nonatomic, copy) void (^block)(id sender);
  17. - (id)initWithBlock:(void (^)(id sender))block;
  18. - (void)invoke:(id)sender;
  19. @end
  20. @implementation _YYUIGestureRecognizerBlockTarget
  21. - (id)initWithBlock:(void (^)(id sender))block{
  22. self = [super init];
  23. if (self) {
  24. _block = [block copy];
  25. }
  26. return self;
  27. }
  28. - (void)invoke:(id)sender {
  29. if (_block) _block(sender);
  30. }
  31. @end
  32. @implementation UIGestureRecognizer (YYAdd)
  33. - (instancetype)initWithActionBlock:(void (^)(id sender))block {
  34. self = [self init];
  35. [self addActionBlock:block];
  36. return self;
  37. }
  38. - (void)addActionBlock:(void (^)(id sender))block {
  39. _YYUIGestureRecognizerBlockTarget *target = [[_YYUIGestureRecognizerBlockTarget alloc] initWithBlock:block];
  40. [self addTarget:target action:@selector(invoke:)];
  41. NSMutableArray *targets = [self _yy_allUIGestureRecognizerBlockTargets];
  42. [targets addObject:target];
  43. }
  44. - (void)removeAllActionBlocks{
  45. NSMutableArray *targets = [self _yy_allUIGestureRecognizerBlockTargets];
  46. [targets enumerateObjectsUsingBlock:^(id target, NSUInteger idx, BOOL *stop) {
  47. [self removeTarget:target action:@selector(invoke:)];
  48. }];
  49. [targets removeAllObjects];
  50. }
  51. - (NSMutableArray *)_yy_allUIGestureRecognizerBlockTargets {
  52. NSMutableArray *targets = objc_getAssociatedObject(self, &block_key);
  53. if (!targets) {
  54. targets = [NSMutableArray array];
  55. objc_setAssociatedObject(self, &block_key, targets, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  56. }
  57. return targets;
  58. }
  59. @end