iOS開發之第三方框架Masonry

第三方框架Masonry

該框架能夠大大簡化AutoLayout使用過程當中對控件添加約束的代碼。 框架地址:https://github.com/SnapKit/Masonrygit

  • 使用步驟
    • 添加Masonry文件夾的全部源代碼到項目中
    • 添加2個宏、導入主頭文件
    // 只要添加了這個宏,就不用帶mas_前綴
    #define MAS_SHORTHAND
    // 只要添加了這個宏,equalTo就等價於mas_equalTo
    #define MAS_SHORTHAND_GLOBALS
    // 這個頭文件必定要放在上面兩個宏的後面
    #import "Masonry.h"
  • mas_equalTo和equalTo的區別: 默認狀況下,mas_equalTo有自動包裝功能,好比自動將20包裝爲@20,equalTo沒有自動包裝功能,若是添加了下面的宏,那麼mas_equalTo和equalTo就沒有區別
#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
  • eg
// 藍色控件
    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);
    }];
相關文章
相關標籤/搜索