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 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
// 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]; | |
}]; |
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];
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
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)