iOS Autolayout按比例调整UIViews的大小?

时间:2013-05-07 15:19:43

标签: ios6 autolayout

我正在努力学习Autolayout,所以我正在阅读教程,并且还在讨论一些UIViews,只是为了看看我能让他们做些什么。我想知道如何通过自动布局实现从纵向到横向过渡的下图?我想,例如,如果我把黄色固定在视图的顶部,蓝色到黄色,橙色到蓝色,橙色到底部,它们会按比例调整大小,保持彼此之间的20个像素以及视图的顶部和底部。但是,例如,蓝色的盒子不会让我将它的支柱移到视图的顶部,即使它被固定在它上面的黄色视图上,所以它会将所有内容向下推到屏幕上。我知道你可以平均高度和高度来调整大小,但有没有办法按比例调整大小,保持它们之间的间距? enter image description here

2 个答案:

答案 0 :(得分:2)

在Interface Builder中制作约束可能会令人沮丧,而Interface Builder还不能使用乘数来制定约束,例如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] ;

答案 1 :(得分:0)

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

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

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

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

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

5)这是因为有时当你给出相等的宽度或高度约束时,第一个视图将是视图本身,有时第一个视图将是另一个视图。这完全取决于您为其他视图设置的其余约束。

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

谢谢。