使用代碼實現(xiàn)Autolayout的方法1
- 創(chuàng)建約束
+(id)constraintWithItem:(id)view1
attribute:(NSLayoutAttribute)attr1
relatedBy:(NSLayoutRelation)relation
toItem:(id)view2
attribute:(NSLayoutAttribute)attr2
multiplier:(CGFloat)multiplier
constant:(CGFloat)c;
* view1 :要約束的控件
* attr1 :約束的類型(做怎樣的約束)
* relation :與參照控件之間的關(guān)系
* view2 :參照的控件
* attr2 :約束的類型(做怎樣的約束)
* multiplier :乘數(shù)
* c :常量
- 添加約束
- (void)addConstraint:(NSLayoutConstraint *)constraint;
- (void)addConstraints:(NSArray *)constraints;
- 注意
- 一定要在擁有父控件之后再添加約束
- 關(guān)閉Autoresizing功能
view.translatesAutoresizingMaskIntoConstraints = NO;
使用代碼實現(xiàn)Autolayout的方法2 - VFL
- 使用VFL創(chuàng)建約束數(shù)組
+ (NSArray *)constraintsWithVisualFormat:(NSString *)format
options:(NSLayoutFormatOptions)opts
metrics:(NSDictionary *)metrics
views:(NSDictionary *)views;
* format :VFL語句
* opts :約束類型
* metrics :VFL語句中用到的具體數(shù)值
* views :VFL語句中用到的控件
- 使用下面的宏來自動生成views和metrics參數(shù)
NSDictionaryOfVariableBindings(...)
使用代碼實現(xiàn)Autolayout的方法3 - Masonry
- 使用步驟
- 添加Masonry文件夾的所有源代碼到項目中
- 添加2個宏罕拂、導(dǎo)入主頭文件
// 只要添加了這個宏,就不用帶mas_前綴 #define MAS_SHORTHAND
// 只要添加了這個宏痰洒,equalTo就等價于mas_equalTo
define MAS_SHORTHAND_GLOBALS
// 這個頭文件一定要放在上面兩個宏的后面
import "Masonry.h"
```
- 添加約束的方法
// 這個方法只會添加新的約束
[view makeConstraints:^(MASConstraintMaker *make) {
}];
// 這個方法會將以前的所有約束刪掉,添加新的約束
[view remakeConstraints:^(MASConstraintMaker *make) {
}];
// 這個方法將會覆蓋以前的某些特定的約束
[view updateConstraints:^(MASConstraintMaker *make) {
}];
- 約束的類型
1.尺寸:width\height\size
2.邊界:left\leading\right\trailing\top\bottom
3.中心點:center\centerX\centerY
4.邊界:edges