Autolayout自動(dòng)布局實(shí)現(xiàn)的方法三:第三方框架Masonry的使用

Masonry

  • Masonry是目前最流行的Autolayout第三方框架,省去了蘋果官方惡心的Autolayout代碼,大大提高了開發(fā)效率。

  • 框架下載地址:https://github.com/SnapKit/Masonry

mas_equalTo和equalTo

  • 默認(rèn)情況下mas_equalTo有自動(dòng)包裝功能,比如自動(dòng)將整型常量30包裝為@30,equalTo沒有自動(dòng)包裝功能
  • 如果添加了下面的宏,那么mas_equalTo和equalTo就沒有區(qū)別:#define MAS_SHORTHAND_GLOBALS(注意:這個(gè)宏一定要添加到#import"Masonry.h"前面否則將沒有效果)。

mas_width和width

  • 默認(rèn)情況下width是make對象的一個(gè)屬性,用來添加寬度約束用的,表示對寬度進(jìn)行約束mas_width是一個(gè)屬性值,用來當(dāng)做equalTo的參數(shù),表示某個(gè)控件的寬度屬性

  • 如果添加了下面的宏,mas_width也可以寫成width

  • defineMAS_SHORTHAND

  • mas_height、mas_centerX以此類推

  • 頭部添加

#import "ViewController.h"
//define this constant if you want to use Masonry without the 'mas_' prefix
#define MAS_SHORTHAND
//define this constant if you want to enable auto-boxing for default syntax
#define MAS_SHORTHAND_GLOBALS
#import "Masonry.h"
  • 代碼部分
// 藍(lán)色控件
    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.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);
    }];

最終顯示效果

豎屏效果

橫屏效果
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容