谈到链式编程和函数式编程, Masonry就是最经典的代表, 没事可以多看看它的源码。
例如:
make.top.equalTo(self.myView).offset(10)
- 像这样通过
.
语法,将需要执行的代码块连续的书写下去, 就是链式编程. 它能使代码简单易读,书写方便. - 像这样
equalTo(self.myView)
通过’()’去调用函数,一般调用完返回的还是这个对象本身, 就是函数式编程.
简单写一下链式编程的逻辑
- 创建一个分类,代码如下:
//
// UILabel+category.h
// DEMO
//
// Created by soliloquy on 2017/8/21.
// Copyright © 2017年 soliloquy. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UILabel (category)
- (UILabel *)mas_makeCustomlabel:(void(^)(UILabel *label))block;
+ (UILabel *)mas_makeCustomlabel:(void(^)(UILabel *label))block;
- (UILabel *(^)(NSString *str))textStr;
- (UILabel *(^)(UIColor *tColor))tColor;
- (UILabel *(^)(NSInteger tFont))tFont;
- (UILabel *(^)(CGRect tFrame))tFrame;
@end
//
// UILabel+category.m
// DEMO
//
// Created by soliloquy on 2017/8/21.
// Copyright © 2017年 soliloquy. All rights reserved.
//
#import "UILabel+category.h"
@implementation UILabel (category)
- (UILabel *)mas_makeCustomlabel:(void(^)(UILabel *label))block {
block(self);
return self;
}
+ (UILabel *)mas_makeCustomlabel:(void(^)(UILabel *label))block {
UILabel *l = [[UILabel alloc]init];
block(l);
return l;
}
- (UILabel *(^)(NSString *str))textStr {
return ^(NSString *str) {
self.text = str;
return self;
};
}
- (UILabel *(^)(UIColor *tColor))tColor {
return ^(UIColor *c){
self.textColor = c;
return self;
};
}
- (UILabel *(^)(NSInteger tFont))tFont {
return ^(NSInteger f) {
self.font = [UIFont systemFontOfSize:f];
return self;
};
}
- (UILabel *(^)(CGRect tFrame))tFrame {
return ^(CGRect tFrame) {
self.frame = tFrame;
return self;
};
}
@end
- 用法如下
//
// ViewController.m
// DEMO
//
// Created by soliloquy on 2017/8/21.
// Copyright © 2017年 soliloquy. All rights reserved.
//
#import "ViewController.h"
#import "UILabel+category.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UILabel *l = [UILabel mas_makeCustomlabel:^(UILabel *label) {
label.tFrame(CGRectMake(10, 100, 300, 100)).tFont(20).tColor([UIColor redColor]).textStr(@"服都是公开活动寺管会我偶的厚厚的回拨后回归hi奥");
}];
[self.view addSubview:l];
}
@end
Github: https://github.com/soliloquy-local/Method-chaining.git
以上就是简单的链式编程和函数式编程的入门思想,更多的还是要通过自己多阅读别人的代码,多去敲。总有一天你会很好的掌握这个思想,成为大神!!!