目的: 以block的形式給button添加點擊事件
使用:
UIButton *btn=[UIButton buttonWithType:UIButtonTypeSystem];
[btn setTitle:title forState:UIControlStateNormal];
[btn addEventHandler:^(id sender) {
} forControlEvents:UIControlEventValueChanged];
實現:
.h
#import <UIKit/UIKit.h>
#import <objc/runtime.h>
typedef void (^ActionBlock)(id sender);
@interface UIControl (Blocks)
- (void)addEventHandler:(ActionBlock)handler forControlEvents:(UIControlEvents)controlEvents;
@end
.m
#import "UIControl+Blocks.h"
static char UIButtonHandlerKey;
@implementation UIControl (Blocks)
- (void)addEventHandler:(ActionBlock)handler forControlEvents:(UIControlEvents)controlEvents
{
objc_setAssociatedObject(self, &UIButtonHandlerKey, handler, OBJC_ASSOCIATION_COPY_NONATOMIC);
[self addTarget:self action:@selector(callActionHandler:) forControlEvents:controlEvents];
}
- (void)callActionHandler:(id)sender
{
ActionBlock handler = (ActionBlock)objc_getAssociatedObject(self, &UIButtonHandlerKey);
if (handler) {
handler(sender);
}
}
@end
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。