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];
}];
@AlbertRenshaw
Copy link

It seems the selector is not unique and this therefor fails when applying to multiple objects (at least for me it did). It looks like a solution was started with selectorId but then not completed? (I may be wrong)

@AbrahamLopezPamias
Copy link

This is my version: can use this code whithout function only need import

#import <objc/runtime.h>

NSString *uuid = [[NSUUID UUID] UUIDString];

IMP implementation = imp_implementationWithBlock(^{

   //Your code here

});

SEL newSelector = @selector(uuid);

class_addMethod([self class], newSelector, implementation, "v@:@");

[!! Your UIButton Here !!:self action:newSelector forControlEvents:UIControlEventTouchUpInside];

@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