2013-05-07 72 views
3

我想学习Autolayout,所以我正在通过教程阅读,并与一些UIViews搞乱,看看我能让他们做些什么。我想知道如何通过自动布局来完成从纵向到横向的过渡,如下图所示?例如,我认为,如果我将黄色固定在视图的顶部,蓝色为黄色,橙色为蓝色,橙色为底部,则它们会按比例调整大小,并保持彼此之间的20个像素以及视图的顶部和底部。但是,例如,蓝色框不会让我将它移到视图的顶部,即使它固定在它上面的黄色视图中,所以它会将所有内容都推下并从横向屏幕中移出。我知道你可以平等地调整高度和宽度来调整大小,但是有什么方法可以按比例调整大小,保持它们之间的距离吗? enter image description hereiOS Autolayout按比例调整UIViews的大小?

回答

2

在界面构建器中制作约束可能令人沮丧,并且界面构建器还不能使用乘数来约束,如blue.height = red.height * 0.5。不过,它们在代码中很容易制作。

我使用Interface Builder来创建和着色UIViews,所以首先我想删除Interface Builder创建的所有约束。

// in UIViewController.m 
[self.view removeConstraints:self.view.constraints] ; 

我将创建一个使用constraintsWithVisualFormat:options:metrics:views:许多制约因素,所以我创建的指针到5个UIViews的字典,并创建一个NSMutableArray持有的约束。

NSDictionary* views = NSDictionaryOfVariableBindings(black, red, yellow, blue, orange) ; 
NSMutableArray* constraints = [NSMutableArray new] ; 

然后我创建一个定位UIViews,并表明具有相同的宽度&高度观点的约束。

[constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[black]-[yellow]-|" options:0 metrics:nil views:views]] ; 
[constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[red(==black)]-[blue(==yellow)]-|" options:0 metrics:nil views:views]] ; 
[constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[orange]-|" options:0 metrics:nil views:views]] ; 
[constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[black]-[red(==black)]-[orange]-|" options:0 metrics:nil views:views]] ; 
[constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[yellow]-[blue]-[orange]-|" options:0 metrics:nil views:views]] ; 

最后,我用乘法器创建约束,并添加所有约束。

[constraints addObject:[NSLayoutConstraint constraintWithItem:orange attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:black attribute:NSLayoutAttributeHeight multiplier:0.5 constant:0]] ; 
[constraints addObject:[NSLayoutConstraint constraintWithItem:yellow attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:black attribute:NSLayoutAttributeHeight multiplier:1.5 constant:0]] ; 
[constraints addObject:[NSLayoutConstraint constraintWithItem:yellow attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:black attribute:NSLayoutAttributeWidth multiplier:1.5 constant:0]] ; 
[self.view addConstraints:constraints] ; 
0

您可以按照以下步骤给出比例高度或宽度约束。

1)首先根据需要给出相等的高度或宽度约束。

2)双击右窗格中的约束或单击约束右侧的“编辑”。

3)像这样改变乘数。如果从宽度100的视图到宽度150的视图添加了相等的宽度约束,则输入乘数150:100。

4)您需要确保不会有关于此约束的任何警告,否则您需要更改乘数,如100:150。

5)发生这种情况是因为有时当您给予等宽或高度约束时,第一个视图将是视图本身,有时第一个视图将会是另一个视图。这完全取决于您为其他视图设置的其余约束条件。

6)现在当正确应用约束时应用其他约束并检查。

谢谢。