Skip to content

Instantly share code, notes, and snippets.

@cconstable
Created June 6, 2013 17:02
Show Gist options
  • Save cconstable/5723099 to your computer and use it in GitHub Desktop.
Save cconstable/5723099 to your computer and use it in GitHub Desktop.
UITapGestureRecognizer + blocks + UIView category = Add tap gestures with ease
// In UIVIew category...
#import <objc/runtime.h>
- (void)addTapGestureWithBlock:(void(^)())wasTappedBlock
{
static int selectorId = 0;
NSString *selectorName = [NSString stringWithFormat:@"tapGestureSelector%d:",selectorId];
IMP implementation = imp_implementationWithBlock(wasTappedBlock);
SEL newSelector = @selector(selectorName);
class_addMethod([self class], newSelector, implementation, "v@:@");
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:newSelector];
[self addGestureRecognizer:tapGesture];
}
// Example Usage
[self.tableView addTapGestureWithBlock:^{
[self.view endEditing:YES];
}];
@didge
Copy link

didge commented Oct 12, 2018

I thought about using this technique until I realized that all those class methods never get cleaned up. It's kind of a terrible idea...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment