一、調用Masonry庫的準備
使用pch文件添加全局宏定義(Pre-Compiled Header)
pch文件即 擴展名為.pch的預編譯文件。是將工程中較穩定的不會經常修改的代碼預先編譯好,放在一個公共的文件(.pch)里。
0>將Masonry文件拖入項目中
1>新建pch文件
2>選中項目-->TARGETS-->Build Setting(選中All)-->搜索prefi
3>雙擊并將pch文件拖入框中
4>設置為Yes
5>填入代碼
#ifndef PrefixHeader_pch
#define PrefixHeader_pch
//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"
// Include any system framework and library headers here that should be included in all compilation units.
// You will also need to set the Prefix Header build setting of one or more of your targets to reference this file.
#endif /* PrefixHeader_pch */
二 、使用方法
1.Masonry屬性
@property (nonatomic, strong, readonly) MASConstraint *left;
@property (nonatomic, strong, readonly) MASConstraint *top;
@property (nonatomic, strong, readonly) MASConstraint *right;
@property (nonatomic, strong, readonly) MASConstraint *bottom;
@property (nonatomic, strong, readonly) MASConstraint *leading;
@property (nonatomic, strong, readonly) MASConstraint *trailing;
@property (nonatomic, strong, readonly) MASConstraint *width;
@property (nonatomic, strong, readonly) MASConstraint *height;
@property (nonatomic, strong, readonly) MASConstraint *centerX;
@property (nonatomic, strong, readonly) MASConstraint *centerY;
@property (nonatomic, strong, readonly) MASConstraint *baseline;
下面是關于這些屬性的介紹
2.約束的類型
1.尺寸:width、height、size
2.邊界:left、leading、right、trailing、top、bottom
3.中心點:center、centerX、centerY
4.邊界:edges
5.偏移量:offset、inset、insets、sizeOffset、centerOffset
6.優先級:priority()約束優先級(0~1000)、priorityLow()\*500*\、priorityMedium()\*500*\、priorityHigh()\*750*\
7.比例:multipliedBy乘因數、 dividedBy除因數
3.兩個區別
1>mas_equalTo
和equalTo
:
默認情況下
mas_equalTo
有自動包裝功能,比如自動將20
包裝為@20
而equalTo
沒有自動包裝功能。
如果添加了下面的宏,那么mas_equalTo
和equalTo
就沒有區別:
#define MAS_SHORTHAND_GLOBALS
2>mas_height
和height
:
默認情況下
width
是make
對象的一個屬性,用來添加寬度約束用的,表示對寬度進行約束。mas_width
是一個屬性值,用來當做equalTo
的參數,表示某個控件的寬度屬性。
如果添加了下面的宏,mas_width
也可以寫成width
:
#define MAS_SHORTHAND
4.基本使用
mas_makeConstraints://添加約束
mas_updateConstraints://更新約束、亦可添加新約束
mas_remakeConstraints://重置之前的約束
[view1 mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(superview).with.insets(padding);
}];
5.注意點
使用
Masonry
不需要設置控件的translatesAutoresizingMaskIntoConstraints
屬性為NO
;
防止block
中的循環引用,使用弱引用(這是錯誤觀點),在這里block
是局部的引用,block
內部引用self
不會造成循環引用的
__weak typeof (self) weakSelf = self;
(沒必要的寫法)