VFL演示樣例
上篇文章向大家介紹了VFL的基本的語法點,假設對下面演示樣例不熟的童鞋,能夠前去參考。廢話不多說。我們直接來看演示樣例。
演示樣例一
將五個大小同樣、顏色不同的view
排成一行,view
間的間隔為15px
,第一個view
的間隔與屏幕的左邊間隔10px
,最后一個view
的間隔與屏幕的右邊間隔也為10px
。
//依據屏幕的寬度。計算view的寬度和高度CGFloat width = ([[UIScreen mainScreen] bounds].size.width-2*10-4*15)/5;CGFloat height = width;//固定第一個viewUIView *firstView = [UIView new];firstView.backgroundColor = [UIColor blackColor];// 將次屬性設置為NO,表示將使用AutoLayout的方式來布局firstView.translatesAutoresizingMaskIntoConstraints = NO;[self.view addSubview:firstView];//------使用VFL為第一個view加入約束------//在水平方向上,讓firstview的左邊與父視圖的左邊間隔10px,且自身寬度為widthNSArray *constraints1 = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[firstView(==width)]" options:0 metrics:@{@"width":@(width)} views:NSDictionaryOfVariableBindings(firstView)];//在垂直方向上,讓firstView的上邊與父視圖的上邊間隔100px,且自身的高度為heightNSArray *constraints2 = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-100-[firstView(==height)]" options:0 metrics:@{@"height":@(height)} views:NSDictionaryOfVariableBindings(firstView)];[self.view addConstraints:constraints1];[self.view addConstraints:constraints2];//定義一個顏色數組NSArray *colors = @[[UIColor redColor],[UIColor orangeColor],[UIColor yellowColor],[UIColor blueColor]];//定義一個views數組NSMutableArray *views = [NSMutableArray array];[views addObject:firstView];for (int i = 0; i < 4; i++) {UIView *view = [UIView new];view.backgroundColor = colors[i];view.translatesAutoresizingMaskIntoConstraints = NO;[self.view addSubview:view];[views addObject:view];}//依次給views數組中的view使用vfl加入約束for (int i = 1; i < views.count; i++) {UIView *view1 = views[i-1];UIView *view2 = views[i];NSDictionary *bindings = NSDictionaryOfVariableBindings(view1,view2);NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:[view1]-15-[view2(==width)]" options:0 metrics:@{@"width":[NSNumber numberWithFloat:width]} views:bindings];[self.view addConstraints:constraints];}UIView *view1 = views[0];for (int i = 0; i < views.count; i++) {UIView *view2 = views[i];NSDictionary *bindings = NSDictionaryOfVariableBindings(view1,view2);NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-100-[view2(==view1)]" options:0 metrics:nil views:bindings];[self.view addConstraints:constraints];}
效果截圖:
下篇演示樣例將會是使用VFL
對登錄界面進行布局,喜歡我的博客的童鞋能夠關注一波!
posted on 2017-07-07 15:51 mthoutai 閱讀(...) 評論(...) 編輯 收藏