該框架能夠大大簡化AutoLayout使用過程當中對控件添加約束的代碼。 框架地址:https://github.com/SnapKit/Masonrygit
// 只要添加了這個宏,就不用帶mas_前綴 #define MAS_SHORTHAND // 只要添加了這個宏,equalTo就等價於mas_equalTo #define MAS_SHORTHAND_GLOBALS // 這個頭文件必定要放在上面兩個宏的後面 #import "Masonry.h"
#define MAS_SHORTHAND_GLOBALS
// 這個方法只會添加新的約束 [view makeConstraints:^(MASConstraintMaker *make) { }]; // 這個方法會將之前的全部約束刪掉,添加新的約束 [view remakeConstraints:^(MASConstraintMaker *make) { }]; // 這個方法將會覆蓋之前的某些特定的約束 [view updateConstraints:^(MASConstraintMaker *make) { }];
1.尺寸:width\height\size 2.邊界:left\leading\right\trailing\top\bottom 3.中心點:center\centerX\centerY 4.邊界:edges
// 藍色控件 UIView *blueView = [[UIView alloc] init]; blueView.backgroundColor = [UIColor blueColor]; [self.view addSubview:blueView]; // 居中(水平+垂直) // 尺寸是父控件的一半 [blueView mas_makeConstraints:^(MASConstraintMaker *make) { make.size.mas_equalTo(self.view).multipliedBy(0.5); make.center.mas_equalTo(self.view); //make.centerX.mas_equalTo(self.view); //make.centerY.mas_equalTo(self.view); }];
// 藍色控件 UIView *blueView = [[UIView alloc] init]; blueView.backgroundColor = [UIColor blueColor]; [self.view addSubview:blueView]; // 紅色控件 UIView *redView = [[UIView alloc] init]; redView.backgroundColor = [UIColor redColor]; [self.view addSubview:redView]; // 添加約束 CGFloat margin = 20; CGFloat height = 50; [blueView makeConstraints:^(MASConstraintMaker *make) { //make就是指前面調用makeConstraints的對象 make.left.equalTo(self.view.left).offset(margin); make.right.equalTo(redView.left).offset(-margin); make.bottom.equalTo(self.view.bottom).offset(-margin); make.height.equalTo(height); make.top.equalTo(redView.top); make.bottom.equalTo(redView.bottom); make.width.equalTo(redView.width); }]; [redView makeConstraints:^(MASConstraintMaker *make) { make.right.equalTo(self.view.right).offset(-margin); }];