Skip to content

Instantly share code, notes, and snippets.

@odrobnik
Created June 4, 2012 00:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save odrobnik/2865589 to your computer and use it in GitHub Desktop.
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
#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