1. 程式人生 > >VFL演示樣例

VFL演示樣例

markdown str ext dsm nds auto 寬度 art object

上篇文章向大家介紹了VFL的基本的語法點,假設對下面演示樣例不熟的童鞋,能夠前去參考。廢話不多說。我們直接來看演示樣例。

演示樣例一

將五個大小同樣、顏色不同的view排成一行,view間的間隔為15px,第一個view的間隔與屏幕的左邊間隔10px,最後一個view的間隔與屏幕的右邊間隔也為10px

//依據屏幕的寬度。計算view的寬度和高度
    CGFloat width = ([[UIScreen mainScreen] bounds].size.width-2*10-4*15)/5;
    CGFloat height = width;

    //固定第一個view
UIView *firstView = [UIView new]; firstView.backgroundColor = [UIColor blackColor]; // 將次屬性設置為NO,表示將使用AutoLayout的方式來布局 firstView.translatesAutoresizingMaskIntoConstraints = NO; [self.view addSubview:firstView]; //------使用VFL為第一個view加入約束------ //在水平方向上,讓firstview的左邊與父視圖的左邊間隔10px,且自身寬度為width
NSArray *constraints1 = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[firstView(==width)]" options:0 metrics:@{@"width":@(width)} views:NSDictionaryOfVariableBindings(firstView)]; //在垂直方向上,讓firstView的上邊與父視圖的上邊間隔100px,且自身的高度為height NSArray *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對登錄界面進行布局,喜歡我的博客的童鞋能夠關註一波!

VFL演示樣例