在iOS 9 / Xcode 7中,这个问题将在IB中轻松解决。只需选择按钮(或其他要垂直分布的内容)并选择编辑器 > 嵌入 > 堆栈视图。然后简单地配置堆栈视图:
- 提供约束以定位和调整堆栈视图本身的大小。例如,将堆栈视图的四个边沿固定到其父视图的四个边沿。
- 设置堆栈视图的属性。在这种情况下,我们希望垂直轴、填充对齐和等间距分布。
就这样!但是,你可能会好奇它是如何工作的,因为手动编码仍然可以完成相同的工作。堆栈视图通过插入空隙引导(spacer guides),而不是插入空隙视图(spacer views)来执行分配操作。引导(UILayoutGuide)是一种轻量级对象,用于布局约束,表现得像视图,但不是视图,因此不必使其无形且不承载任何视图开销。
为了说明这一点,我将在代码中实现堆栈视图的功能。假设我们有四个要垂直分布的视图。我们为它们分配了除了分配外的所有约束:
- 它们都有绝对高度的约束
- 它们的左侧固定在父视图的左侧,右侧固定在父视图的右侧
- 顶部视图的顶部固定在父视图的顶部,底部视图的底部固定在父视图的底部
现在,假设我们有四个视图的引用作为一个数组:
views
,那么:
let guides = [UILayoutGuide(), UILayoutGuide(), UILayoutGuide()]
for guide in guides {
self.view.addLayoutGuide(guide)
}
NSLayoutConstraint.activateConstraints([
guides[1].heightAnchor.constraintEqualToAnchor(guides[0].heightAnchor),
guides[2].heightAnchor.constraintEqualToAnchor(guides[0].heightAnchor),
guides[0].widthAnchor.constraintEqualToConstant(10),
guides[1].widthAnchor.constraintEqualToConstant(10),
guides[2].widthAnchor.constraintEqualToConstant(10),
guides[0].leftAnchor.constraintEqualToAnchor(self.view.leftAnchor),
guides[1].leftAnchor.constraintEqualToAnchor(self.view.leftAnchor),
guides[2].leftAnchor.constraintEqualToAnchor(self.view.leftAnchor),
views[0].bottomAnchor.constraintEqualToAnchor(guides[0].topAnchor),
views[1].bottomAnchor.constraintEqualToAnchor(guides[1].topAnchor),
views[2].bottomAnchor.constraintEqualToAnchor(guides[2].topAnchor),
views[1].topAnchor.constraintEqualToAnchor(guides[0].bottomAnchor),
views[2].topAnchor.constraintEqualToAnchor(guides[1].bottomAnchor),
views[3].topAnchor.constraintEqualToAnchor(guides[2].bottomAnchor)
])
显然,我可以使用循环使代码更加简洁和精炼,但是我为了清晰起见特意展开了循环,以便您可以看到模式和技术。