1. 程式人生 > >Masonry部分用法(控件數組等間隔排序)

Masonry部分用法(控件數組等間隔排序)

divide arduino sco htm req 並且 高度 發的 groov

(轉自)http://www.jianshu.com/p/1d1a1165bb04

簡要

自動布局最重要的是約束:UI元素間關系的數學表達式。約束包括尺寸、由優先級和閾值管理的相對位置。它們是添加劑,可能導致約束沖突 、約束不足造成布局無法確定 。這兩種情況都會產生異常。

使用前:AutoLayout關於更新的幾個方法的區別

  • setNeedsLayout:告知頁面需要更新,但是不會立刻開始更新。執行後會立刻調用layoutSubviews。
  • layoutIfNeeded:告知頁面布局立刻更新。所以一般都會和setNeedsLayout一起使用。如果希望立刻生成新的frame需要調用此方法,利用這點一般布局動畫可以在更新布局後直接使用這個方法讓動畫生效。
  • layoutSubviews:系統重寫布局
  • setNeedsUpdateConstraints:告知需要更新約束,但是不會立刻開始
  • updateConstraintsIfNeeded:告知立刻更新約束
  • updateConstraints:系統更新約束

使用

1. 基本使用

  • mas_makeConstraints:添加約束
  • mas_updateConstraints:更新約束、亦可添加新約束
  • mas_remakeConstraints:重置之前的約束

  • multipler屬性表示約束值為約束對象的乘因數, dividedBy屬性表示約束值為約束對象的除因數,可用於設置view的寬高比

    // 進行屏幕的適配的時候,往往需要根據屏幕寬度來適配一個相應的高度,在此推薦使用如下約束的方式來進行控件的適配
    [self.topView addSubview:self.topInnerView];
    [self.topInnerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(self.topView.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);
    }];
  • priorityLow()設置約束優先級
  • #define MAS_SHORTHAND_GLOBALS使用全局宏定義,可以使equalTo等效於mas_equalTo
  • #define MAS_SHORTHAND使用全局宏定義, 可以在調用masonry方法的時候不使用mas_前綴
// 這裏註意到一個地方,就是當使用了這個全局宏定義之後,發現可以有個類`NSArray+MASAdditions.h`,看了之後發現可以
self.buttonViews = @[ raiseButton, lowerButton, centerButton ];
// 之後可以在updateConstraints 方法中
- (void)updateConstraints {
   [self.buttonViews updateConstraints:^(MASConstraintMaker *make) {
        make.baseline.equalTo(self.mas_centerY).with.offset(self.offset);
    }];
    [super updateConstraints];  
}
  • 動態修改視圖約束:
    // 創建視圖約束
    [blueView mas_makeConstraints:^(MASConstraintMaker *make) {
          self.animatableConstraint = make.edges.equalTo(superview).insets(paddingInsets).priorityLow();
    ]];
    // 更改約束 (另一處方法中)
    UIEdgeInsets paddingInsets = UIEdgeInsetsMake(padding, padding, padding, padding);
    self.animatableConstraint.insets = paddingInsets;
    [self layoutIfNeeded];
  • debug模式:
    // 對某個view添加key值
    greenView.mas_key = @"greenView";
    // 或者如下順序
    MASAttachKeys(greenView, redView, blueView, superview);
    // 同樣的對每條約束亦可以添加key
    make.height.greaterThanOrEqualTo(@5000).key(@"ConstantConstraint");
  • preferredMaxLayoutWidth: 多行label的約束問題
// 已經確認好了位置
// 在layoutSubviews中確認label的preferredMaxLayoutWidth值
- (void)layoutSubviews {
    [super layoutSubviews];
    // 你必須在 [super layoutSubviews] 調用之後,longLabel的frame有值之後設置preferredMaxLayoutWidth
    self.longLabel.preferredMaxLayoutWidth = self.frame.size.width-100;
    // 設置preferredLayoutWidth後,需要重新布局
    [super layoutSubviews];
}
  • scrollView使用約束的問題:原理通過一個contentView來約束scrollView的contentSize大小,也就是說以子控件的約束條件,來控制父視圖的大小
// 1. 控制scrollView大小(顯示區域)
[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的大小
  • 新方法: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;

使用方法很簡單,因為它是NSArray的類擴展:

//  創建水平排列圖標 arr中放置了2個或連個以上的初始化後的控件
//  alongAxis 軸線方向   固定間隔     頭部間隔      尾部間隔
[arr mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:20 leadSpacing:5 tailSpacing:5];
[arr mas_makeConstraints:^(MASConstraintMaker *make) {
       make.top.equalTo(@60);
       make.height.equalTo(@60);
}];

2. 註意事項

  • 約束視圖對象只有在被addSubview之後,才能給視圖添加約束
  • 當你的所有約束都在 updateConstraints 內調用的時候,你就需要在此調用此方法,因為 updateConstraints方法是需要觸發的
// 調用在view 內部,而不是viewcontroller
+ (BOOL)requiresConstraintBasedLayout {
    return YES;
}

/**
 *  蘋果推薦 約束 增加和修改 放在此方法種
 */
- (void)updateConstraints {
    [self.growingButton updateConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self);
        make.width.equalTo(@(self.buttonSize.width)).priorityLow();
        make.height.equalTo(@(self.buttonSize.height)).priorityLow();
        make.width.lessThanOrEqualTo(self);
        make.height.lessThanOrEqualTo(self);
    }];
    //最後記得回調super方法
    [super updateConstraints];
}
  • 如果想要約束變換之後實現動畫效果,則需要執行如下操作
    // 通知需要更新約束,但是不立即執行
    [self setNeedsUpdateConstraints];
    // 立即更新約束,以執行動態變換
    // update constraints now so we can animate the change
    [self updateConstraintsIfNeeded];
    // 執行動畫效果, 設置動畫時間
    [UIView animateWithDuration:0.4 animations:^{
       [self layoutIfNeeded];
    }];

一般的布局

    self.letfView = [UIView new];
    self.letfView.backgroundColor = [UIColor redColor];
    self.rightView = [UIView new];
    self.rightView.backgroundColor = [UIColor greenColor];

    [self.view addSubview:self.letfView];
    [self.view addSubview:self.rightView];

    [self.letfView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view).mas_offset(10);// leftView 左邊 = self.view 左邊 +10
        make.top.mas_equalTo(self.view).mas_offset(20);// leftView 上邊 = self.view 上邊 +20
        make.height.mas_equalTo(100);// leftView 高 = 100
    }];

    [self.rightView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.letfView);// rightView 上邊 = leftView 上邊(即上邊對齊)
        make.right.mas_equalTo(self.view).mas_offset(-10);// rightView 右邊 = self.view 右邊 - 10
        make.left.mas_equalTo(self.letfView.mas_right).mas_offset(20);// rightView 左邊 = leftView 右邊 + 20
        make.width.mas_equalTo(self.letfView);// rightView 寬 = leftView 寬
        make.height.mas_equalTo(self.letfView);// rightView 高 = leftView 高
    }];

// 實現了最基礎的 左右2個View 等高等寬等簡單約束,在橫豎屏切換通用。

到這裏,基本上已經可以開始玩masonry了,看完更多屬性,基本小學畢業了。

更多 make.XXX ,先手比較屬性。

left; 左
top; 上
right; 右
bottom; 下
leading; 左
trailing; 右
width; 寬
height; 高
centerX; x軸中心
centerY; y軸中心
baseline; 基線,沒怎麽用過

leftMargin; 左邊默認邊距好像是20,下面的類似
rightMargin;
topMargin;
bottomMargin;
leadingMargin;
trailingMargin;
centerXWithinMargins;
centerYWithinMargins;

----------- 分割線 ----------

edges;4周
size;大小
center;中心
對應語法略有不同,偏移方法也相對復雜一些。不偏移的話使用可以與上面一致。

更多mas_equalTo(XXX) ,後手比較屬性

上半部分 基本雷同,如果不添加,就是默認與前面make.XXX 對應的mas_
mas_left;
mas_top;
mas_right;
mas_bottom;
mas_leading;
mas_trailing;
mas_width;
mas_height;
mas_centerX;
mas_centerY;
mas_baseline;

mas_leftMargin;
mas_rightMargin;
mas_topMargin;
mas_bottomMargin;
mas_leadingMargin;
mas_trailingMargin;
mas_centerXWithinMargins;
mas_centerYWithinMargins;

----------- 分割線 ----------

自動根據bar 高度設置的引導屬性值,舉個例子:
存在navigationBar 時,mas_topLayoutGuideBottom 相當於 增加了44。
不存在navigationBar 時,mas_topLayoutGuideBottom 相對於 0 。

mas_topLayoutGuide;// navgationBar 相關,
mas_topLayoutGuideTop;
mas_topLayoutGuideBottom;

mas_bottomLayoutGuide;// tabbar toolbar 相關
mas_bottomLayoutGuideTop;
mas_bottomLayoutGuideBottom;

多條件布局

  • 大於、小於、等於
mas_equalTo; =
mas_greaterThanOrEqualTo; >=
mas_lessThanOrEqualTo; <=
// 大小於,使用場景感覺比較少。
  • 約束優先級
簡單舉例:原本2個View是上下排布,當topView 移除時,bottomView,就使用次級約束而上移。

    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.and.right.and.left.mas_equalTo(self.view);
        make.height.mas_equalTo(100);
    }];

    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.topView.mas_bottom).priority(999);// 可以自己寫優先值,越大越優先(1000 是xib 默認值,也是系統默認最大值)
        make.top.mas_equalTo(self.view).priorityLow();// 也可以用系統默認的優先值,low 代表250

        make.left.and.right.mas_equalTo(self.view);
        make.height.mas_equalTo(100);
    }];
  • 同時多個屬性一致簡寫
// 使用 and 鏈接屬性
make.left.and.top.and.width.and.height.mas_equalTo(self.letfView);
  • 同時與多個View存在關系,混合寫
// 數組形式    make.top.mas_equalTo(@[self.letfView.mas_top,self.rightView.mas_top]);
  • mas_equalTo(XXX) 的 mas_width 與 width 比較
// mas_ 前綴的 是宏定義,封裝好了直接可以使用 NSInteger,
// 而沒有前綴的 需要使用 NSNumber
        make.width.mas_equalTo(100);
        make.width.equalTo(@100);
  • mas_offset 與 with.offset 相比較
    UIEdgeInsets edg = UIEdgeInsetsMake(10, 20, 30, 40);

    [self.letfView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view).mas_offset(edg);
        make.edges.mas_equalTo(self.view).with.insets(edg);

    }];

// 使用 with. 需要區分 offset、insets、sizeOffset、centerOffset,分別使用偏移。
// 使用mas_offset 自動區分了上面的幾種情況,自動匹配了

關於 偏移 可以繼續研究CoreGraphice 框架中的 CGGeometry,下次在寫。

更新 重置約束 - 可以實現動畫效果

設置約束三大方法

mas_makeConstraints 添加某個
mas_updateConstraints 更新某個
mas_remakeConstraints 重置全部
  • 簡單更新約束
    // 原本 約束
    [self.letfView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.and.right.and.left.mas_equalTo(self.view);
        make.height.mas_equalTo(100);
    }];

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 更新約束
    [self.letfView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).mas_offset(300);
    }];
  • 結合平移動畫
    // 修改 上面的 更新約束的方法,
    [self.letfView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).mas_offset(300);
    }];

    [self.letfView setNeedsLayout]; // 標記需要更新約束
    [UIView animateWithDuration:1. animations:^{
        [self.letfView layoutIfNeeded]; // 動畫過程中更新約束,達到偏移效果
    }];

布局涉及的其他屬性 - 內容抗壓縮,內容緊湊

(我的理解,叫法可能不一樣)

舉個例子:同水平方向有2 個 Label,內容都不確定有多少,即寬度不定。

  • 對2個Label 進行不定寬的布局,如果僅僅這樣布局,對內容的控制,可能不是我們想要的。但是好像沒有報錯。可能默認處理了。(我這裏嘗試與第一個label 抗壓縮,第二個label 內容優先緊湊,效果一致。)
    [self.leftLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.and.left.mas_equalTo(self.view);
    }];

    [self.rightLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.and.right.mas_equalTo(self.view);
        make.left.mas_equalTo(self.leftLabel.mas_right);
    }];
  • 對Label 添加屬性
(個人覺得第一步是這個:先顯示內容)
    // 內容緊湊 - 優先完全顯示內容,且不多占像素。
    [self.leftLabel setContentHuggingPriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisHorizontal];
    [self.rightLabel setContentHuggingPriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];



// (個人覺得第二步是這個:調整內容是否壓縮)
    // 抵抗 壓縮,抗壓縮低的,在上一步的基礎上,進行壓縮調整。
    [self.leftLabel setContentCompressionResistancePriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisHorizontal];
    [self.rightLabel setContentCompressionResistancePriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];

http://tutuge.me/2015/08/08/autolayout-example-with-masonry2/

Masonry部分用法(控件數組等間隔排序)