Created
June 4, 2012 00:21
-
-
Save odrobnik/2865589 to your computer and use it in GitHub Desktop.
Please comment: adding tap and long press action with blocks to any view
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <objc/runtime.h> | |
@implementation UIView (DTActionHandlers) | |
- (id)tapActionBlock | |
{ | |
return objc_getAssociatedObject(self, "DTActionHandlerTap"); | |
} | |
- (void)addTapActionWithBlock:(void (^)(void))block | |
{ | |
if (![self tapActionBlock]) | |
{ | |
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(__handleTapAction:)]; | |
[self addGestureRecognizer:tap]; | |
} | |
objc_setAssociatedObject(self, "DTActionHandlerTap", block, OBJC_ASSOCIATION_COPY); | |
} | |
- (void)__handleTapAction:(UITapGestureRecognizer *)gesture | |
{ | |
if (gesture.state == UIGestureRecognizerStateRecognized) | |
{ | |
void (^block)(void) = [self tapActionBlock]; | |
if (block) | |
{ | |
block(); | |
} | |
} | |
} | |
- (id)longPressActionBlock | |
{ | |
return objc_getAssociatedObject(self, "DTActionHandlerLongPress"); | |
} | |
- (void)addLongPressActionWithBlock:(void (^)(void))block | |
{ | |
if (![self longPressActionBlock]) | |
{ | |
UILongPressGestureRecognizer *tap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(__handleLongPressAction:)]; | |
[self addGestureRecognizer:tap]; | |
} | |
objc_setAssociatedObject(self, "DTActionHandlerLongPress", block, OBJC_ASSOCIATION_COPY); | |
} | |
- (void)__handleLongPressAction:(UILongPressGestureRecognizer *)gesture | |
{ | |
if (gesture.state == UIGestureRecognizerStateBegan) | |
{ | |
void (^block)(void) = [self longPressActionBlock]; | |
if (block) | |
{ | |
block(); | |
} | |
} | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment