Autolayout 總結

使用代碼實現Autolayout的方法1

  • 建立約束
+(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 :與參照控件之間的關係
* view2 :參照的控件
* attr2 :約束的類型(作怎樣的約束)
* multiplier :乘數
* c :常量
  • 添加約束
- (void)addConstraint:(NSLayoutConstraint *)constraint;
- (void)addConstraints:(NSArray *)constraints;
  • 注意
    • 必定要在擁有父控件以後再添加約束
    • 關閉Autoresizing功能
    view.translatesAutoresizingMaskIntoConstraints = NO;

使用代碼實現Autolayout的方法2 - VFL

  • 使用VFL建立約束數組
+ (NSArray *)constraintsWithVisualFormat:(NSString *)format
options:(NSLayoutFormatOptions)opts
metrics:(NSDictionary *)metrics
views:(NSDictionary *)views;
* format :VFL語句
* opts :約束類型
* metrics :VFL語句中用到的具體數值
* views :VFL語句中用到的控件
  • 使用下面的宏來自動生成views和metrics參數
NSDictionaryOfVariableBindings(...)

使用代碼實現Autolayout的方法3 - Masonry

  • 使用步驟
    • 添加Masonry文件夾的全部源代碼到項目中
    • 添加2個宏、導入主頭文件
    // 只要添加了這個宏,就不用帶mas_前綴
    #define MAS_SHORTHAND

// 只要添加了這個宏,equalTo就等價於mas_equalTo數組

define MAS_SHORTHAND_GLOBALS

// 這個頭文件必定要放在上面兩個宏的後面code

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
相關文章
相關標籤/搜索