masonry是现在项目中常用的自动布局第三方库,使用方法一般如下:
[otherDetectView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.and.right.equalTo(self.view);
make.top.equalTo(lbaddItem.mas_bottom).offset(10);
make.height.mas_equalTo(2*(buttonHeight+10)+10);
}];
之所以有这种方便直观而又神奇的用法,是因为masonry的实现方法中包含了 链式编程思想
,具体可以谷歌百度。
我模仿masonry写了一个计算器的demo,具体代码如下:
计算器管理器
// 计算器管理器(链式编程思想)
#import <Foundation/Foundation.h>
@class CaculatorMaker;
@interface NSObject (CalculatorManager)
//计算
+ (float)makCalulator:(void(^)(CaculatorMaker *make)) caaulatorMaker;
@end
#import "NSObject+CalculatorManager.h"
#import "CaculatorMaker.h"
@implementation NSObject (CalculatorManager)
+ (float)makCalulator:(void (^)(CaculatorMaker *))caaulatorMaker {
CaculatorMaker *mgr = [CaculatorMaker new];
caaulatorMaker(mgr);
return mgr.result;
}
@end
CaculatorMaker
#import <Foundation/Foundation.h>
@interface CaculatorMaker : NSObject
@property (nonatomic,assign) float result;
//加法
- (CaculatorMaker *(^)(float))add;
//减
- (CaculatorMaker *(^)(float))sub;
//乘
- (CaculatorMaker *(^)(float))muilt;
//除
- (CaculatorMaker *(^)(float))divide;
@end
#import "CaculatorMaker.h"
@implementation CaculatorMaker
- (CaculatorMaker *(^)(float))add {
return ^CaculatorMaker *(float value) {
_result += value;
return self;
};
}
- (CaculatorMaker *(^)(float))sub {
return ^CaculatorMaker *(float value) {
_result -= value;
return self;
};
}
- (CaculatorMaker *(^)(float))muilt {
return ^CaculatorMaker *(float value) {
_result *= value;
return self;
};
}
- (CaculatorMaker *(^)(float))divide {
return ^CaculatorMaker *(float value) {
_result /= value;
return self;
};
}
@end
使用
float result = [NSObject makCalulator:^(CaculatorMaker *make) {
make.add(1).add(5).sub(4).muilt(2).divide(3);
}];