那天抽风想自己看看链式编程的实现~~前有RAC太强大好使,我这纯粹看看思路,就当看着玩~
UIButton *btn = [[UIButton alloc] init];
btn.xl_frame(CGRectMake(0, 0, 80, 30)).xl_title(@"测试一把~~");
[btn addActionBlock:^(UIButton *btn) {
LOG(@"点击了~~咋地!");
} forControlEvents:(UIControlEventTouchUpInside)];
1.UIButton+XLBlock.h 文件
#import <UIKit/UIKit.h>
typedef void(^BtnActionBlock)(UIButton *btn);
typedef UIButton *(^XLBtnFrameBlock)(CGRect frame);
typedef UIButton *(^XLBtnTitleBlock)(NSString *title);
@interface UIButton (XLBlock)
@property (nonatomic, copy)XLBtnFrameBlock xl_frame;
@property (nonatomic, copy)XLBtnTitleBlock xl_title;
-(void)addActionBlock:(BtnActionBlock)actionBlock forControlEvents:(UIControlEvents)event;
@end
1.UIButton+XLBlock.m 文件
#import "UIButton+XLBlock.h"
#import <objc/runtime.h>
@implementation UIButton (XLBlock)
#pragma mark -- 点语法实现链式调用(测试学习代码原理)
#pragma mark -- frame的处理:(只是处理 [返回当前对象并携带要处理当前对象参数变量的block] 的get方法)
-(XLBtnFrameBlock)xl_frame{
XLBtnFrameBlock block = ^(CGRect frame){//get方法里定义block
self.frame = frame;
return self;
};
return block;
}
-(void)setXl_frame:(XLBtnFrameBlock)xl_frame{
//空实现
}
#pragma mark -- title的处理
-(XLBtnTitleBlock)xl_title{
XLBtnTitleBlock block = ^(NSString *title){
[self setTitle:title forState:UIControlStateNormal];
return self;
};
return block;
}
-(void)setXl_title:(XLBtnTitleBlock)xl_title{
//空实现
}
-(void)addActionBlock:(BtnActionBlock)actionBlock forControlEvents:(UIControlEvents)event{
__weak typeof(self) weakSelf = self;
if (actionBlock){
objc_setAssociatedObject(self, "BtnActionBlock", actionBlock, OBJC_ASSOCIATION_COPY);//KVC增加示例变量
}
[self addTarget:weakSelf action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
}
- (void)btnAction:(UIButton *)btn
{
BtnActionBlock block = objc_getAssociatedObject(self, "BtnActionBlock");//取出实例变量
if (block) {
block(btn);
}
}
网友评论