Masonry的簡單使用

以前使用過masonry做頁面布局,長時間不用,有些使用方法就有些遺忘了,所以今天就簡單的復(fù)習(xí)一下

Masonry 源碼:https://github.com/SnapKit/Masonry

一、masonry的屬性和系統(tǒng)屬性對應(yīng)關(guān)系

MASViewAttribute NSLayoutAttribute
mas_left NSLayoutAttributeLeft
mas_top NSLayoutAttributeTop
mas_right NSLayoutAttributeRight
mas_bottom NSLayoutAttributeBottom
mas_leading NSLayoutAttributeLeading
mas_trailing NSLayoutAttributeTrailing
mas_width NSLayoutAttributeWidth
mas_height NSLayoutAttributeHeight
mas_centerX NSLayoutAttributeCenterX
mas_centerY NSLayoutAttributeCenterY
mas_baseline NSLayoutAttributeBaseline
mas_firstBaseline NSLayoutAttributeFirstBaseline
mas_lastBaseline NSLayoutAttributeLastBaseline
mas_leftMargin NSLayoutAttributeLeftMargin
mas_rightMargin NSLayoutAttributeRightMargin
mas_topMargin NSLayoutAttributeTopMargin
mas_bottomMargin NSLayoutAttributeBottomMargin
mas_leadingMargin NSLayoutAttributeLastBaseline
mas_trailingMargin NSLayoutAttributeLastBaseline
mas_centerXWithinMargins NSLayoutAttributeCenterXWithinMargins
mas_centerYWithinMargins NSLayoutAttributeCenterYWithinMargins

二、基本使用

1.添加約束

mas_makeConstraints: 只負責(zé)添加約束 使用元素必須已經(jīng)添加到父視圖上
mas_updateConstraints: 更新在block中出現(xiàn)的約束 不會導(dǎo)致出現(xiàn)兩個相同約束的情況
mas_remakeConstraints: 清除之前所有的約束只保留新的約束

下面是常用的使用方法

//分別設(shè)置各個相對邊距(superview為view的父類視圖,下同)
make.left.mas_equalTo(superView.mas_left).mas_offset(10);
make.right.mas_equalTo(superView.mas_right).mas_offset(-10);
make.top.mas_equalTo(superView.mas_top).mas_offset(10);
make.bottom.mas_equalTo(superView.mas_bottom).offset(-10);

//直接使用left大于等于每個值
make.left.mas_greaterThanOrEqualTo(10);

//設(shè)置寬和高
make.width.mas_equalTo(60);
make.height.mas_equalTo(60);

//.設(shè)置center和寬高比
make.center.mas_equalTo(superView);
make.width.mas_equalTo(superView).multipliedBy(1.00/3);
make.height.mas_equalTo(superView).multipliedBy(0.25);

//.關(guān)于約束優(yōu)先級,此處要注意約束沖突的問題,統(tǒng)一約束優(yōu)先級大的生效
make.left.mas_equalTo(100);
make.left.mas_equalTo(view.superview.mas_left).offset(10);
make.left.mas_equalTo(20).priority(700);
make.left.mas_equalTo(40).priorityHigh();
make.left.mas_equalTo(60).priorityMedium();
make.left.mas_equalTo(80).priorityLow();

//.如果你想讓view的(x坐標)左邊大于等于label的左邊,以下兩個約束的寫法效果一樣
 make.left.greaterThanOrEqualTo(label);
 make.left.greaterThanOrEqualTo(label.mas_left);
  • 上左為正,下右為負: 是因為坐標而來的 視圖坐標左上為原點 X向右為正 Y向下為正
  • priorityLow():設(shè)置約束優(yōu)先級(0-1000)
    注:默認通過mas_make添加的約束不設(shè)置優(yōu)先級時,默認都是最高(1000)
  • #define MAS_SHORTHAND_GLOBALS:使用全局宏定義(需要放在.pch文件中),可以使equalTo- 等效于mas_equalTo(要在#import masonry.h 之前)
  • #define MAS_SHORTHAND:使用全局宏定義(需要放在.pch文件中), 可以在調(diào)用masonry方法的時候不使用mas_前綴(要在#import masonry.h 之前)

2.mas_equalTo和equalTo區(qū)別

#define mas_equalTo(...) equalTo(MASBoxValue((__VA_ARGS__)))
#define equalTo(...) mas_equalTo(__VA_ARGS__)

前者比后者多了類型轉(zhuǎn)換操作,支持CGSize CGPoint NSNumber UIEdgeinsets。
mas_equalTo是equalTo的封裝,equalTo適用于基本數(shù)據(jù)類型,而mas_equalTo適用于類似UIEdgeInsetsMake 等復(fù)雜類型,基本上它可以替換equalTo。

make.left.equalTo(@10) 需要使用字面量
make.left.mas_equalTo(10) 不需要使用字面量

3.同時創(chuàng)建多個約束

Masonry提供了一些便利的方法供我們同時創(chuàng)建多個不同的約束,他們被稱為MASCompositeConstraints,如:

edges
// 使一個view的top, left, bottom, right 等于view2的
make.edges.equalTo(view2);

//相對于superviewde上左下右邊距分別為5,10,15,20
make.edges.equalTo(superview).insets(UIEdgeInsetsMake(5, 10, 15, 20))
size
// 使得寬度和高度大于等于 titleLabel
make.size.greaterThanOrEqualTo(titleLabel)

// 相對于superview寬度大100,高度小50
make.size.equalTo(superview).sizeOffset(CGSizeMake(100, -50))
center
//中心與button1對齊
make.center.equalTo(button1)

//水平方向中心相對向左偏移5,豎直方向中心向下偏移10
make.center.equalTo(superview).centerOffset(CGPointMake(-5, 10))

你可以在約束鏈里添加相應(yīng)的view來增加代碼的可讀性:
// 除了top,所有的邊界與superview對齊
make.left.right.and.bottom.equalTo(superview);

make.top.equalTo(otherView);

4.mas_topLayoutGuide 和 mas_bottomLayoutGuide

// self是一個控制器
// 兩種效果不同
make.top.equalTo(self.view);// 這樣寫效果是 topView 與 狀態(tài)欄的y值相等
make.top.equalTo(self.mas_topLayoutGuide);

// 此時兩種效果相同
make.bottom.equalTo(self.mas_bottomLayoutGuide);
make.bottom.equalTo(self.view);

5.requiresConstraintBasedLayout

如果你把一個View的所有的約束建立在updateconstraints,
你可能永遠不會得到updateconstraints的約束。
若要解決此問題,請重寫requiresConstraintBasedLayout返回YES,
如果視圖窗口需要使用基于約束的布局

+ (BOOL)requiresConstraintBasedLayout
{
    return YES;
}

6. multipliedBy和dividedBy

multipliedBy屬性:表示約束值為約束對象的乘因數(shù)
dividedBy屬性:表示約束值為約束對象的除因數(shù)

可用于設(shè)置view的寬高比
使用multipliedBy必須是對同一個控件本身

[self.topInnerView mas_makeConstraints:^(MASConstraintMaker *make) {
 // 寬高比1.0/3.0     
    make.width.equalTo(self.topInnerView.mas_height).multipliedBy(3);
// 寬高比3.0/1.0       
    make.width.equalTo(self.topInnerView.mas_height).dividedBy(3);
    make.width.and.height.lessThanOrEqualTo(self.topView);
    make.width.and.height.equalTo(self.topView).with.priorityLow();
    make.center.equalTo(self.topView);
}];

7. 動態(tài)修改視圖約束:

// 創(chuàng)建視圖約束
[blueView mas_makeConstraints:^(MASConstraintMaker *make) {
      //self.animatableConstraint = make.edges.equalTo(superview).insets(paddingInsets).priorityLow();
      self.animatableConstraint = make.edges.equalTo(superview).insets(paddingInsets);
]];

// 更改約束 (另一處方法中)
UIEdgeInsets paddingInsets = UIEdgeInsetsMake(padding, padding, padding, padding);
self.animatableConstraint.insets = paddingInsets;
[UIView animateWithDuration:1.0 animations:^{
       [self.view layoutIfNeeded];
}];

8. debug模式:

// 對某個view添加key值
greenView.mas_key = @"greenView";
// 或者如下順序
MASAttachKeys(greenView, redView, blueView, superview);
// 同樣的對每條約束亦可以添加key
make.height.greaterThanOrEqualTo(@5000).key(@"ConstantConstraint");

eg:
便于定位具體哪個約束

    [greenBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).insets(paddingInsets);
        make.width.equalTo(@200).key(@"greenBtn__ConstantConstraint");
    }];

打?。?/p>

9. preferredMaxLayoutWidth: 多行l(wèi)abel的約束問題

// 已經(jīng)確認好了位置
// 在layoutSubviews中確認label的preferredMaxLayoutWidth值
-(void)layoutSubviews {
    [super layoutSubviews];
    // 你必須在 [super layoutSubviews] 調(diào)用之后,longLabel的frame有值之后設(shè)置preferredMaxLayoutWidth
    self.longLabel.preferredMaxLayoutWidth = self.frame.size.width-100;
    // 設(shè)置preferredLayoutWidth后,需要重新布局
    [super layoutSubviews];
}

10. scrollView使用約束的問題:

原理是通過一個contentView來約束scrollView的contentSize大小,也就是說以子控件的約束條件,來控制父視圖的大小

// 1\. 控制scrollView大?。@示區(qū)域)
[self.scrollView makeConstraints:^(MASConstraintMaker *make) {
     make.edges.equalTo(self.view);
}];
// 2\. 添加一個contentView到scrollView,并且添加好約束條件
[contentView makeConstraints:^(MASConstraintMaker *make) {
     make.edges.equalTo(self.scrollView);
     // 注意到此處的寬度約束條件,這個寬度的約束條件是比添加項
     make.width.equalTo(self.scrollView);
}];
// 3\. 對contentView的子控件做好約束,達到可以控制contentView的大小

11. 2個或2個以上的控件等間隔排序

注釋:

/**
 *  多個控件固定間隔的等間隔排列,變化的是控件的長度或者寬度值
 *
 *  @param axisType        軸線方向
 *  @param fixedSpacing    間隔大小
 *  @param leadSpacing     頭部間隔
 *  @param tailSpacing     尾部間隔
 */
- (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType 
                    withFixedSpacing:(CGFloat)fixedSpacing l
                          eadSpacing:(CGFloat)leadSpacing 
                         tailSpacing:(CGFloat)tailSpacing;

/**
 *  多個固定大小的控件的等間隔排列,變化的是間隔的空隙
 *
 *  @param axisType        軸線方向
 *  @param fixedItemLength 每個控件的固定長度或者寬度值
 *  @param leadSpacing     頭部間隔
 *  @param tailSpacing     尾部間隔
 */
- (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType 
                 withFixedItemLength:(CGFloat)fixedItemLength 
                         leadSpacing:(CGFloat)leadSpacing 
                         tailSpacing:(CGFloat)tailSpacing;

eg: masonry官方Demo

//  創(chuàng)建水平排列圖標 
//  arr: 中放置了2個或連個以上的初始化后的控件
//  type: 0~3,四種舉例
    switch (type) {
        case 0:
            [arr mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:20 leadSpacing:5 tailSpacing:5];
            [arr makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(@60);
                make.height.equalTo(@60);
            }];
            break;
        case 1:
            [arr mas_distributeViewsAlongAxis:MASAxisTypeVertical withFixedSpacing:20 leadSpacing:5 tailSpacing:5];
            [arr makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(@0);
                make.width.equalTo(@60);
            }];
            break;
        case 2:
            [arr mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedItemLength:30 leadSpacing:200 tailSpacing:30];
            [arr makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(@60);
                make.height.equalTo(@60);
            }];
            break;
        case 3:
            [arr mas_distributeViewsAlongAxis:MASAxisTypeVertical withFixedItemLength:30 leadSpacing:30 tailSpacing:200];
            [arr makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(@0);
                make.width.equalTo(@60);
            }];
            break;

        default:
            break;

    }

12.如果想要約束變換之后實現(xiàn)動畫效果,則需要執(zhí)行如下操作

// 通知需要更新約束,但是不立即執(zhí)行
[self setNeedsUpdateConstraints];
// 立即更新約束,以執(zhí)行動態(tài)變換
// update constraints now so we can animate the change
[self updateConstraintsIfNeeded];
// 執(zhí)行動畫效果, 設(shè)置動畫時間
[UIView animateWithDuration:0.4 animations:^{
   [self layoutIfNeeded];
}];

參考:

Masonry使用歸納總結(jié)

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

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

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