#import <objc/runtime.h>

typedef void (^buttonAction)(UIButton *sender);
@implementation UIButton (BlockAction)

+ (UIButton *) buttonWithType:(UIButtonType)type andAction:(buttonAction)action  forControlEvents:(UIControlEvents)controlEvents; {
    
    UIButton * button = [UIButton buttonWithType:type];
    
    // suppress undeclared selector warning or else '@selector(action:)' will complain.
    // because it doesnt actually exist...yet.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
    
    // pull out IMP implementation from the block.
    IMP blockImp = imp_implementationWithBlock(action);
    
    // add the instance method with the name 'action:' and the arguement type of UIBUttion *
    class_addMethod(UIButton.class, @selector(action:), blockImp, @encode(UIButton *));
    
    // add action like you normally would.
    [button addTarget:button action:@selector(action:) forControlEvents:controlEvents];
    
#pragma clang diagnostic pop
    
    return button;
}