您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 程式設計技術

iOS 布局新利器:Masonry 快速上手實戰

編輯:iOS 程式設計技術

近來項目中試了試 Masonry,體驗相當不錯——比手寫 frame 快得多,又避開了 Storyboard 和 xib 裡那堆讓人頭疼的可視化約束。

先來看效果圖。以前看到這種九宮格布局就頭痛,各種坐標計算讓人崩潰;用 Masonry,幾分鐘的事。

完整代碼

用的還不算熟練,有不少走了彎路的地方,歡迎指正。

#import "HomeView.h"
#import <Masonry.h>

@implementation HomeView

@synthesize myEquipmentBtn, aboutCompanyBtn, errorRecordingBtn,
            equipmentStateBtn, remoteControlBtn, equipmentGraphBtn, guideBtn;

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        [self setUpSubViews];
    }
    return self;
}

- (void)setUpSubViews {
    /**
     * 創建子視圖並添加
     * 使用Masonry必須先把控件初始化,然後添加到共同的父視圖上
     */

    //我的設備
    myEquipmentBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [myEquipmentBtn setBackgroundImage:[UIImage imageNamed:@"1"] forState:0];
    [self addSubview:myEquipmentBtn];

    //關於我們
    aboutCompanyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [aboutCompanyBtn setBackgroundImage:[UIImage imageNamed:@"3"] forState:0];
    [self addSubview:aboutCompanyBtn];

    //故障記錄
    errorRecordingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [errorRecordingBtn setBackgroundImage:[UIImage imageNamed:@"6"] forState:0];
    [self addSubview:errorRecordingBtn];

    //設備狀態
    equipmentStateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [equipmentStateBtn setBackgroundImage:[UIImage imageNamed:@"2"] forState:0];
    [self addSubview:equipmentStateBtn];

    //遠程控制
    remoteControlBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [remoteControlBtn setBackgroundImage:[UIImage imageNamed:@"4"] forState:0];
    [self addSubview:remoteControlBtn];

    //設備曲線圖
    equipmentGraphBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [equipmentGraphBtn setBackgroundImage:[UIImage imageNamed:@"5"] forState:0];
    [self addSubview:equipmentGraphBtn];

    //使用說明
    guideBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [guideBtn setBackgroundImage:[UIImage imageNamed:@"guide"] forState:0];
    [self addSubview:guideBtn];

    /**
     * 約束
     */

    //我的設備
    [myEquipmentBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        //上邊距離父視圖上邊5個單位
        make.top.equalTo(self.mas_top).with.offset(5);
        //左邊距離父視圖左邊0個單位
        make.left.equalTo(self.mas_left).with.offset(0);
        //寬等於父視圖寬的0.5倍,multipliedBy設定比例
        make.width.equalTo(self.mas_width).with.multipliedBy(0.5);
        //高等於父視圖高的0.2倍
        make.height.equalTo(self.mas_height).with.multipliedBy(0.2);
    ];

    //關於我們
    [aboutCompanyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        //上邊距離上部控件的底邊5個單位
        make.top.equalTo(myEquipmentBtn.mas_bottom).with.offset(5);
        //左邊距離父視圖左邊0個單位
        make.left.equalTo(self.mas_left).with.offset(0);
        //寬和上方的控件一樣寬
        make.width.equalTo(myEquipmentBtn.mas_width);
        //高是父視圖高的0.4倍
        make.height.equalTo(self.mas_height).with.multipliedBy(0.4);
    ];

    //故障記錄
    [errorRecordingBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        //上邊距離上部控件的底邊5個單位
        make.top.equalTo(aboutCompanyBtn.mas_bottom).with.offset(5);
        //左邊距離父視圖左邊0個單位
        make.left.equalTo(self.mas_left).with.offset(0);
        //等寬
        make.width.equalTo(myEquipmentBtn.mas_width);
        //下邊距離父視圖下邊-5個單位
        //+5的話控件就跑出父視圖之外了,-5說明在父視圖裡面
        make.bottom.equalTo(self.mas_bottom).with.offset(-5);
    ];

    //設備狀態
    [equipmentStateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_top).with.offset(5);
        make.left.equalTo(myEquipmentBtn.mas_right).with.offset(5);
        make.right.equalTo(self.mas_right).with.offset(0);
        make.height.equalTo(self.mas_height).with.multipliedBy(0.15);
    ];

    //遠程控制
    [remoteControlBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(equipmentStateBtn.mas_bottom).with.offset(5);
        make.left.equalTo(myEquipmentBtn.mas_right).with.offset(5);
        make.width.equalTo(equipmentStateBtn.mas_width);
        make.height.equalTo(self.mas_height).with.multipliedBy(0.15);
    };

    //設備曲線圖
    [equipmentGraphBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(remoteControlBtn.mas_bottom).with.offset(5);
        make.left.equalTo(myEquipmentBtn.mas_right).with.offset(5);
        make.width.equalTo(remoteControlBtn.mas_width);
        make.height.equalTo(self.mas_height).with.multipliedBy(0.23);
    };

    //使用說明
    [guideBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(equipmentGraphBtn.mas_bottom).with.offset(5);
        make.left.equalTo(myEquipmentBtn.mas_right).with.offset(5);
        make.width.equalTo(remoteControlBtn.mas_width);
        make.bottom.equalTo(self.mas_bottom).with.offset(-5);
    };
}

@end

Masonry 常用 API 速查

1. 三個約束入口

  • mas_makeConstraints: —— 添加約束,只能調用一次,二次調用會導致已有約束被移除後重建;
  • mas_updateConstraints: —— 更新約束的常量(constant),只更新不新增;
  • mas_remakeConstraints: —— 先移除全部已有約束再重新添加,適合狀態切換場景。

選錯方法是很常見的錯誤來源:想改 offset 卻用了 remake,會把其他約束一起清掉。

2. 常用屬性與方法

make.top / bottom / left / right / width / height
make.centerX / centerY
make.edges.equalTo(view).insets(UIEdgeInsetsMake(...))

// 三種關係表達
.equalTo(view)              // 等於
.mas_greaterThanOrEqualTo() // 大於等於
.mas_lessThanOrEqualTo()    // 小於等於

// 兩種運算修飾
.with.offset(10)                  // 加常量
.with.multipliedBy(0.5)           // 乘比例

3. 忽視 Auto Layout 的控件

UIView 默認 translatesAutoresizingMaskIntoConstraints 為 NO,但使用 Masonry 時不需要手動設置——它內部已經幫你處理了。不過如果混用了原生 NSLayoutConstraint,還是要注意這個屬性。

寫這段代碼時踩到的坑

坑一:offset 的正負號

註釋裡寫得很清楚:右邊、下邊的約束要用負值。make.bottom.equalTo(self.mas_bottom).with.offset(-5) 表示距底部還有 5 個單位;寫成 +5 控件就會跑到父視圖外面去。這是新手最常犯的錯誤。

坑二:各控件高度比例不一致

上面這份代碼裡,左邊三個按鈕的高度用了 0.2、0.4、0.23,右邊三個用 0.15、0.15、0.23。這些比例是反覆調出來的,並不是嚴謹的設計——真實項目中更推薦先確定一個基準值(比如按鈕高度固定 60pt),再用 make.height.equalTo(myEquipmentBtn) 保持等高等寬,這樣改設計稿時只需要動一處。

坑三:百分比約束的時機

用 multipliedBy 依賴父視圖尺寸時,父視圖自身必須已經有確定的 frame 或約束。如果在父視圖尺寸還不確定時就添加這類約束,會出現布局警告甚至位置錯亂。

為什麼 Masonry 值得用

對比手寫 frame:需要手動處理屏幕旋轉、多設備適配、狀態欄高度變化,任何一處改動都可能引發連鎖計算。

對比 Storyboard:避免了三方合併衝突,代碼可複用性更強,也能擺脫「打開 xib 就卡住」的困擾。

對比原生 NSLayoutConstraint:語法從 constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant: 這種冗長形式變成了鏈式表達,可讀性提升明顯。

值得一提的是,Masonry 只是對 Auto Layout 的語法封裝,底層生成的仍然是 NSLayoutConstraint。因此它並不能繞過 Auto Layout 的性能開銷——在 cell 極度複雜的長列表裡,這仍然是需要關注的問題。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved