AutoLayout的各種使用方法

2021-07-10 14:54:49 字數 2650 閱讀 9197

關於autolayout

下面通過乙個簡單的列子分別演示autolayout的各種使用方法

需求是在控制器view底部新增2個view,1個藍色,1個紅色2個view寬度、高度永遠相等距離父控制項左邊、右邊、下邊間距和2個view之間的間距相等,效果如下圖

橫屏效果

橫屏效果

豎屏效果

豎屏效果

在xib於storyboard中建立約束的方法

用oc**建立同樣的約束

用vfl語言來建立約束

uiview *redview = [[uiview alloc] init];

redview.backgroundcolor = [uicolor redcolor];

redview.translatesautoresizingmaskintoconstraints = no;

[self

.view addsubview:redview];

uiview *blueview = [[uiview alloc] init];

blueview.backgroundcolor = [uicolor bluecolor];

blueview.translatesautoresizingmaskintoconstraints = no;

[self

.view addsubview:blueview];

nsnumber *margin = @50;

//水平方向的約束

nsstring *vfl_h = @"h:|-margin-[redview]-margin-[blueview(==redview)]-margin-|";

nsdictionary *views = nsdictionaryofvariablebindings(blueview, redview);

nsdictionary *metrics = nsdictionaryofvariablebindings(margin);

nsarray *layoutconstraintharr = [nslayoutconstraint

constraintswithvisualformat:vfl_h

options:nslayoutformatalignallbottom | nslayoutformatalignalltop

metrics:metrics views:views];

[self

.view addconstraints:layoutconstraintharr];

nsnumber *height = @80;

//垂直方向的約束

nsstring *vfl_v = @"v:[redview(height)]-margin-|";

nsdictionary *metrics2 = nsdictionaryofvariablebindings(height, margin);

nsarray *layoutconstraintvarr = [nslayoutconstraint

constraintswithvisualformat:vfl_v

options:kniloptions

metrics:metrics2 views:views];

[self

.view addconstraints:layoutconstraintvarr];

用masonry(一款非常非常優秀的開源框架)

資源鏈結

uiview *redview = [[uiview alloc] init];

redview.backgroundcolor = [uicolor redcolor];

[self.view addsubview:redview];

uiview *blueview = [[uiview alloc] init];

blueview.backgroundcolor = [uicolor bluecolor];

[self.view addsubview:blueview];

[redview makeconstraints:^(masconstraintmaker *make) ];

[blueview makeconstraints:^(masconstraintmaker *make) ];

以上就是幾種autolayout的實現方法,個人覺的方法2,方法3如果不需要維護老專案的**可以先不用掌握,用masonry可以很快掌握autolayout的使用技巧,希望文章能幫助到大家。

AutoLayout的各種使用方法

關於autolayout 下面通過乙個簡單的列子分別演示autolayout的各種使用方法 需求是在控制器view底部新增2個view,1個藍色,1個紅色2個view寬度 高度永遠相等距離父控制項左邊 右邊 下邊間距和2個view之間的間距相等,效果如下圖 橫屏效果 橫屏效果 豎屏效果 豎屏效果 在...

AutoLayout的使用及介紹

為什麼會出現autoresizingmask和autolayout?1.適配 適應 相容各種不同的情況 系統適配 新的方法 舊的方法廢棄 螢幕適配 針對不同大小螢幕尺寸進行適配 1 點 畫素的關係 在使用者眼中 螢幕是由無數個畫素組成的 畫素越多,螢幕越清晰 在開發者眼中 螢幕是由無數個點組成的,點...

Auto Layout 入門及使用

引言 auto layout是ios6發布後引入的乙個全新的布局特性,其目的是彌補以往autoresizing在布局方面的不足之處,以及未來應對更多尺寸適配介面時布局可以更好的展示.要完全掌握auto layout 以下簡稱al 不是一件容易的事情,實踐是學習和掌握的根本,並且在根本上面,理解其如何...