Created
December 12, 2012 07:38
-
-
Save ammmir/4265830 to your computer and use it in GitHub Desktop.
A category on UIControl that makes it easy to handle control events with blocks, instead of target-action selectors.
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
#import <UIKit/UIKit.h> | |
@interface UIControl (BlockActions) | |
- (id)addHandlerForControlEvents:(UIControlEvents)controlEvents block:(void(^)(id))aBlock; | |
- (void)removeHandlerForControlEventsWithToken:(id)aToken; | |
@end |
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
#import <objc/runtime.h> | |
#import "UIControl+BlockActions.h" | |
@implementation UIControl (BlockActions) | |
- (id)addHandlerForControlEvents:(UIControlEvents)controlEvents block:(void (^)(id))aBlock { | |
static NSUInteger counter = 0; | |
NSString *identifier = [NSString stringWithFormat:@"internalBlockAction_%d:", counter++]; | |
SEL blockSelector = NSSelectorFromString(identifier); | |
IMP wrapper = imp_implementationWithBlock(^(id sender, SEL cmd) { | |
aBlock(sender); | |
}); | |
class_addMethod([self class], blockSelector, wrapper, "v@:"); | |
[self addTarget:self action:blockSelector forControlEvents:controlEvents]; | |
return identifier; | |
} | |
- (void)removeHandlerForControlEventsWithToken:(id)aToken { | |
// since we can't really remove methods at runtime, just fake it | |
class_replaceMethod([self class], | |
NSSelectorFromString(aToken), | |
imp_implementationWithBlock(^(id realSelf, SEL cmd) {}), | |
"v@:"); | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment