Skip to content

Instantly share code, notes, and snippets.

@rcomblen
Forked from joshdholtz/UIButton+Block.h
Created May 30, 2012 09:54
Show Gist options
  • Save rcomblen/2835270 to your computer and use it in GitHub Desktop.
Save rcomblen/2835270 to your computer and use it in GitHub Desktop.
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]];
}];
..
@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