OC runtime UIButton扩展Block点击事件

From: http://www.jianshu.com/p/d4eab6815ac2

主要实现通过runtime动态关联属性。
上码!!!!

#import <UIKit/UIKit.h>

typedef void(^ButtonBlock)(UIButton* btn);

@interface UIButton (Block)

/**
 *  button 添加点击事件
 *
 *  @param block
 */
- (void)addAction:(ButtonBlock)block;

/**
 *  button 添加事件
 *
 *  @param block
 *  @param controlEvents 点击的方式
 */
- (void)addAction:(ButtonBlock)block forControlEvents:(UIControlEvents)controlEvents;

@end

////////////////////////////////////////////////////


#import "UIButton+Block.h"

#import <objc/runtime.h>

@implementation UIButton (Block)
static char ActionTag;

/**
 *  button 添加点击事件 默认点击方式UIControlEventTouchUpInside
 *
 *  @param block
 */
- (void)addAction:(ButtonBlock)block {
    objc_setAssociatedObject(self, &ActionTag, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
    [self addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
}

/**
 *  button 添加事件
 *
 *  @param block
 *  @param controlEvents 点击的方式
 */
- (void)addAction:(ButtonBlock)block forControlEvents:(UIControlEvents)controlEvents {
    objc_setAssociatedObject(self, &ActionTag, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
    [self addTarget:self action:@selector(action:) forControlEvents:controlEvents];
}

/**
 *  button 事件的响应方法
 *
 *  @param sender 
 */
- (void)action:(id)sender {
    ButtonBlock blockAction = (ButtonBlock)objc_getAssociatedObject(self, &ActionTag);
    if (blockAction) {
        blockAction(self);
    }
}
@end

使用方法如下

UIButton *testButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
testButton.backgroundColor = [UIColor redColor];
[self.view addSubview:testButton];

[testButton addAction:^(UIButton *btn) {
    NSLog(@"我被点名了");
}];

[testButton addAction:^(UIButton *btn) {
     NSLog(@"我被点名了");
} forControlEvents:UIControlEventTouchUpInside];
Author

陈昭

Posted on

2017-06-08

Updated on

2021-12-27

Licensed under

You need to set install_url to use ShareThis. Please set it in _config.yml.
You forgot to set the business or currency_code for Paypal. Please set it in _config.yml.

Kommentare

You forgot to set the shortname for Disqus. Please set it in _config.yml.