实用链式编程演示 iOS
一、简单理解:
链式编程的直观表现是我们可以使用点语法一直获取这个对象的属性并赋值,比如Masonry。
实现的思路是我们定义get方法时,让这个方法返回一个block,而block的返回值为当前对象,这样每当我们执行完这个方法得到的永远是当前对象,然后就可以继续使用点语法调用其他方法。
二、代码演示
这里我们演示一个设置设置frame的例子
我们定义一个UIView的分类如下:
@interfaceUIView (Frame)
- (UIView*(^)(CGFloat))x;
- (UIView*(^)(CGFloat))y;
- (UIView*(^)(CGFloat))w;
- (UIView*(^)(CGFloat))h;
.m中的实现如下:
@implementation UIView (Frame)
- (UIView*(^)(CGFloat))x{
__weak typeof(self) weakSelf = self;
UIView*(^blockName)(CGFloat) = ^(CGFloatx) {
CGRectframe = weakSelf.frame;
frame.origin.x = x;
weakSelf.frame = frame;
returnweakSelf;
};
returnblockName;
}
- (UIView*(^)(CGFloat))y {
__weak typeof(self) weakSelf = self;
UIView*(^blockName)(CGFloat) = ^(CGFloaty) {
CGRectframe = weakSelf.frame;
frame.origin.y = y;
weakSelf.frame = frame;
returnweakSelf;
};
returnblockName;
}
- (UIView*(^)(CGFloat))w {
__weak typeof(self) weakSelf = self;
UIView*(^blockName)(CGFloat) = ^(CGFloatw) {
CGRectframe = weakSelf.frame;
frame.size.width = w;
weakSelf.frame = frame;
returnweakSelf;
};
returnblockName;
}
- (UIView*(^)(CGFloat))h {
__weak typeof(self) weakSelf = self;
UIView*(^blockName)(CGFloat) = ^(CGFloath) {
CGRectframe = weakSelf.frame;
frame.size.height = h;
weakSelf.frame = frame;
returnweakSelf;
};
returnblockName;
}
三、使用方式
UIButton *btn = [UIButton buttonWithType:UIButtonTypeContactAdd];
btn.backgroundColor = [UIColor redColor];
[self.viewaddSubview:btn];
btn.x(10).y(333).w(100).h(100).w(200).x(80);
btn.x(10)是执行block,执行之后block返回的是当前的view。