#UIButton+EventBlocks
It's a simple category to implement event handler based in blocks.
Usage
#import "UIButton+EventBlocks.h"
button.onTouchUpInside = ^(UIButton *button, UIEvent *event)
{
// do something...
}
Also you can unlisten events if you pass nil
as value for onTouchUpInside
button.onTouchUpInside = nil;
It's a very simple implementation for UIControlEventTouchUpInside
, you can add blocks for any events you want, for example to add a handler block for UIControlEventTouchDown
event, follow the steps:
@property (nonatomic, copy) UIEventBlock onTouchDown;
@dynamic onTouchDown;
@interface UIButton (_EventBlocks_)
- (void)button:(UIButton *)button touchUpInsideWithEvent:(UIEvent *)event;
- (void)button:(UIButton *)button touchDownWithEvent:(UIEvent *)event;
@end
static void *onTouchDownKey = &onTouchDownKey;
- (void)setOnTouchDown:(UIEventBlock)onTouchDown
{
// If you pass nil
if(onTouchDown)
{
objc_setAssociatedObject(self, onTouchDownKey, onTouchDown, OBJC_ASSOCIATION_COPY_NONATOMIC);
[self addTarget:self action:@selector(button:touchDownWithEvent:) forControlEvents:UIControlEventTouchDown];
}
else
{
objc_setAssociatedObject(self, onTouchDownKey, nil, OBJC_ASSOCIATION_COPY_NONATOMIC);
[self removeTarget:self action:@selector(button:touchDownWithEvent:) forControlEvents:UIControlEventTouchDown];
}
}
- (UIEventBlock)onTouchDown
{
return objc_getAssociatedObject(self, onTouchDownKey);
}
- (void)button:(UIButton *)button touchDownWithEvent:(UIEvent *)event
{
self.onTouchDown(button, event);
}
Yes there is many steps to implement more callbacks but this will be handy in your day and this category is flexible enough for any project.