Button是我们最常见的控件了下面看下常规用法
- (void)viewDidLoad {
[super viewDidLoad];
[self createView];
// Do any additional setup after loading the view.
}
- (void)createView{
UIButton * mybutton = [UIButton buttonWithType:UIButtonTypeCustom];
mybutton.frame=CGRectMake(50,300,40,20);
[mybutton setTitle:@"test" forState:UIControlStateNormal];
[mybutton setBackgroundColor:[UIColor orangeColor]];
[mybutton addTarget:self action:@selector(dealButtonAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:mybutton];
}
//button点击事件
-(void)dealButtonAction:(UIButton*)bu{
NSLog(@"处理点击事件");
}
每一个Button 都要对应一个对应的方法,如果有十个八个button的话那么创建十个八个方法的话,那的多乱,多么的难找
细想一下.如果Button 能这样
[mybutton addEventHandler:^{
NSLog(@"处理点击事件");
} forControlEvents:UIControlEventTouchUpInside];
是不是很神奇
那怎么才能办到呢
- button 添加了方法要用到分类
- button 新方法进行了事件绑定用到了RunTimes
话不多说 上代码
#import <UIKit/UIKit.h>
#import <objc/runtime.h>
/** 事件回调的block */
typedef void (^UIButtonBlock) (void);
NS_ASSUME_NONNULL_BEGIN
@interface UIButton (block)
@property (nonatomic,copy)UIButtonBlock touchAction;
- (void)addEventHandler:(void (^)(void))block forControlEvents:(UIControlEvents)controlEvents;
@end
//------- 漂亮的分割线 -------//
#import "UIButton+block.h"
@implementation UIButton (block)
//------- 添加属性 -------//
static void *touchActionKey = &touchActionKey;
- (UIButtonBlock)touchAction{
return objc_getAssociatedObject(self, &touchActionKey);
}
- (void)setTouchAction:(UIButtonBlock)touchAction{
objc_setAssociatedObject(self, &touchActionKey, touchAction, OBJC_ASSOCIATION_COPY);
}
/**
给按钮绑定事件回调block
@param block 回调的block
@param controlEvents 回调block的事件
*/
- (void)addEventHandler:(void (^)(void))block forControlEvents:(UIControlEvents)controlEvents {
self.touchAction = block;
[self addTarget:self action:@selector(blcokButtonClicked) forControlEvents:controlEvents];
}
// 按钮点击
- (void)blcokButtonClicked {
if (self.touchAction) {
self.touchAction();
}
}
button扩展了一个带block回调的方法,然后绑定了对应的事件,就是有点复杂.
是不是很神奇 , 如果你感觉这样很好玩,那么下面的一个叫RAC的东西,更方便更高效
pod导入
pod 'ReactiveObjC', '~> 3.0.0'
头文件
#import <ReactiveObjC.h>
开始用
[[mybutton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
NSLog(@"处理点击事件");
}];
是不是很简洁,那么下面请看
RAC初探