鏈式編程思想特點:方法返回值必須要有方法調(diào)用者!!
一、Masonry 使用
- (void)viewDidLoad {
[super viewDidLoad];
//創(chuàng)建一個View
UIView * redView = [[UIView alloc]init];
redView.backgroundColor = [UIColor redColor];
[self.view addSubview:redView];
//添加約束 -- make約束制造者!!
[redView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.top.equalTo(@10);
make.right.bottom.equalTo(@-10);
}];
}
二、mas_makeConstraints 執(zhí)行流程
- 創(chuàng)建約束制造者MASConstraintMaker,并且綁定控件,生成一個保存所有約束的數(shù)組;
- 執(zhí)行mas_makeConstraints傳入的Block;
- 讓約束制造者安裝約束!
#import "View+MASAdditions.h"
- (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *))block {
self.translatesAutoresizingMaskIntoConstraints = NO;
//1、建約束制造者MASConstraintMaker,并且綁定控件
MASConstraintMaker *constraintMaker = [[MASConstraintMaker alloc] initWithView:self];
//2、執(zhí)行mas_makeConstraints傳入的Block
block(constraintMaker);
//3、讓約束制造者安裝約束!
return [constraintMaker install];
}
#import "MASConstraintMaker.h"
- (id)initWithView:(MAS_VIEW *)view {
self = [super init];
if (!self) return nil;
self.view = view;
//1、生成一個保存所有約束的數(shù)組
self.constraints = NSMutableArray.new;
return self;
}
三、讓約束制造者安裝約束!
* 3.1 清空之前的所有約束
* 3.2 遍歷約束數(shù)組,一個一個安裝
#import "MASConstraintMaker.h"
- (NSArray *)install {
//1. 清空之前的所有約束
if (self.removeExisting) {
NSArray *installedConstraints = [MASViewConstraint installedConstraintsForView:self.view];
for (MASConstraint *constraint in installedConstraints) {
[constraint uninstall];
}
}
//2. 遍歷約束數(shù)組,一個一個安裝
NSArray *constraints = self.constraints.copy;
for (MASConstraint *constraint in constraints) {
constraint.updateExisting = self.updateExisting;
[constraint install];
}
[self.constraints removeAllObjects];
return constraints;
}
四、自己實現(xiàn)鏈式編程
準備做一個整數(shù)加法計算器,支持連綴,使用鏈式編程思想。
** 主要步驟 **
- 創(chuàng)建一個加法計算器(SumManager);
- 執(zhí)行傳入的Block;
- 返回計算結(jié)果
+ (int)hk_makeConstraints:(void (^)(SumManager *))block
{
//1. 創(chuàng)建一個加法計算器(SumManager)
SumManager * mgr = [[SumManager alloc]init];
2. 執(zhí)行傳入的Block
block(mgr);
3. 返回計算結(jié)果
return mgr.result;
}
加法計算器
** 注意要點 **:
- 方法返回值必須是方法調(diào)用者,即返回SumManager對象;
- 為了使用點語法調(diào)用add()方法,必須使用“有參數(shù)有返回值的Block ”作為返回值
#import <Foundation/Foundation.h>
@interface SumManager : NSObject
/** 結(jié)果 */
@property(assign, nonatomic) int result;
// 為了使用點語法調(diào)用add()方法,必須使用“有參數(shù)有返回值的Block ”(SumManager *(^)(int value))作為返回值
- (SumManager *(^)(int value))add;
@end
#import "SumManager.h"
@implementation SumManager
- (SumManager * (^)(int value))add {
return ^(int value){
_result += value;
//方法返回值必須是方法調(diào)用者
return self;
};
}
@end