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

标签 ios6 autolayout

我正在尝试学习 Autolayout,所以我正在通读教程,同时也在摆弄一些 UIView,看看我能让它们做什么。我想知道如何使用自动布局完成从纵向到横向的过渡,如下图所示?我想,例如,如果我将黄色固定到 View 的顶部,将蓝色固定到黄色,将橙色固定到蓝色,将橙色固定到底部,它们将按比例调整大小,彼此之间保持 20 像素以及 View 的顶部和底部。但是,例如,蓝色框不会让我将其支撑到 View 的顶部,即使它固定在其上方的黄色 View 中,所以它会将所有内容向下推到横向屏幕之外。我知道你可以固定高度和宽度来调整它们的大小,但是有没有办法按比例调整大小,保持它们之间的间距? enter image description here

最佳答案

在 Interface Builder 中进行约束可能会令人沮丧,Interface Builder 还不能对乘数进行约束,例如 blue.height = red.height * 0.5。不过,它们都很容易用代码制作。

我使用 Interface Builder 创建 UIView 并为其着色,所以首先我想删除 Interface Builder 创建的所有约束。

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

我将使用 constraintsWithVisualFormat:options:metrics:views: 创建许多约束,因此我创建了一个指向 5 个 UIView 的指针字典,并创建了一个 NSMutableArray 来保存约束。

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

然后我创建定位 UIView 的约束并指示具有相同宽度和高度的 View 。

[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] ;

关于ios6 - iOS Autolayout 按比例调整 UIViews 的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16422715/

相关文章:

ios - UIScrollView 中的 UITableView 加载所有单元格

iphone - UIView 动画在 View 消失时停止,在重新出现时不会恢复

ios - 自动布局 UILabel

ios - 以编程方式将 View 的前缘与约束对齐

ios - 如何使用堆栈 View 来自动布局标签和按钮?

ios - NSLayoutConstraint 抛出异常 "is not a key in the views dictionary"

iphone - IOS 不编码加号 (+) 登录 x-www-form-urlencoded POST 请求?

ios - 自定义对象的初始化返回null

iphone - 用户选择共享或取消后,iOS Google+ 应用程序不会返回应用程序

ios - UITableView页脚高度问题