Created
June 6, 2013 17:02
-
-
Save cconstable/5723099 to your computer and use it in GitHub Desktop.
UITapGestureRecognizer + blocks + UIView category = Add tap gestures with ease
This file contains 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
// 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]; | |
}]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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...