UIGestureRecognizer+YYAdd.m 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 <objc/runtime.h>
  13. static const int block_key;
  14. @interface _YYUIGestureRecognizerBlockTarget : NSObject
  15. @property (nonatomic, copy) void (^block)(id sender);
  16. - (id)initWithBlock:(void (^)(id sender))block;
  17. - (void)invoke:(id)sender;
  18. @end
  19. @implementation _YYUIGestureRecognizerBlockTarget
  20. - (id)initWithBlock:(void (^)(id sender))block{
  21. self = [super init];
  22. if (self) {
  23. _block = [block copy];
  24. }
  25. return self;
  26. }
  27. - (void)invoke:(id)sender {
  28. if (_block) _block(sender);
  29. }
  30. @end
  31. @implementation UIGestureRecognizer (YYAdd)
  32. - (instancetype)initWithActionBlock:(void (^)(id sender))block {
  33. self = [self init];
  34. [self addActionBlock:block];
  35. return self;
  36. }
  37. - (void)addActionBlock:(void (^)(id sender))block {
  38. _YYUIGestureRecognizerBlockTarget *target = [[_YYUIGestureRecognizerBlockTarget alloc] initWithBlock:block];
  39. [self addTarget:target action:@selector(invoke:)];
  40. NSMutableArray *targets = [self _yy_allUIGestureRecognizerBlockTargets];
  41. [targets addObject:target];
  42. }
  43. - (void)removeAllActionBlocks{
  44. NSMutableArray *targets = [self _yy_allUIGestureRecognizerBlockTargets];
  45. [targets enumerateObjectsUsingBlock:^(id target, NSUInteger idx, BOOL *stop) {
  46. [self removeTarget:target action:@selector(invoke:)];
  47. }];
  48. [targets removeAllObjects];
  49. }
  50. - (NSMutableArray *)_yy_allUIGestureRecognizerBlockTargets {
  51. NSMutableArray *targets = objc_getAssociatedObject(self, &block_key);
  52. if (!targets) {
  53. targets = [NSMutableArray array];
  54. objc_setAssociatedObject(self, &block_key, targets, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  55. }
  56. return targets;
  57. }
  58. @end