Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
iOS - UIButton+Block
//
// UIButton+Block.h
// BoothTag
//
// Created by Josh Holtz on 4/22/12.
// Copyright (c) 2012 Josh Holtz. All rights reserved.
//
#define kUIButtonBlockTouchUpInside @"TouchInside"
#import <UIKit/UIKit.h>
@interface UIButton (Block)
@property (nonatomic, strong) NSMutableDictionary *actions;
- (void) setAction:(NSString*)action withBlock:(void(^)())block;
@end
//
// UIButton+Block.m
// BoothTag
//
// Created by Josh Holtz on 4/22/12.
// Copyright (c) 2012 Josh Holtz. All rights reserved.
//
#import "UIButton+Block.h"
#import "/usr/include/objc/runtime.h"
@implementation UIButton (Block)
static char overviewKey;
@dynamic actions;
- (void) setAction:(NSString*)action withBlock:(void(^)())block {
if ([self actions] == nil) {
[self setActions:[[NSMutableDictionary alloc] init]];
}
[[self actions] setObject:[block copy] forKey:action];
if ([kUIButtonBlockTouchUpInside isEqualToString:action]) {
[self addTarget:self action:@selector(doTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
}
}
- (void)setActions:(NSMutableDictionary*)actions {
objc_setAssociatedObject (self, &overviewKey,actions,OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSMutableDictionary*)actions {
return objc_getAssociatedObject(self, &overviewKey);
}
- (void)doTouchUpInside:(id)sender {
void(^block)();
block = [[self actions] objectForKey:kUIButtonBlockTouchUpInside];
block();
}
...
[button setAction:kUIButtonBlockTouchUpInside withBlock:^{
NSString* launchUrl = @"http://joshholtz.com";
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: launchUrl]];
}];
..
@leviathan
Copy link

leviathan commented Mar 21, 2013

UIButton+Block.m is missing an @EnD statement

@tkirby
Copy link

tkirby commented Jun 9, 2014

Leaks memory in a couple places.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment