UIStackView
iOS9引入了UIStackView
,Apple文档对UIStackView的定义如下:
1 | The UIStackView class provides a streamlined interface for laying out a collection of views in either a column or a row. Stack views let you leverage the power of Auto Layout, creating user interfaces that can dynamically adapt to the device’s screen size, and any changes in the available space |
即,利用UIStackView
我们可以很方便地垂直或水平排列多个subview。
配置UIStackView
UIStackView
有以下几个配置选项让我们来配置它:
Axis
:表示水平排列还是垂直排列Alignment
:控制subview的对齐方式Distribution
:控制subview的分布方式Spacing
:subview间的最小距离
Alignment
因Axis
而异,用图示说明更加形象。
水平排列

垂直排列


注意
UIStackView
会被当成一个Container View,它不会像其他UIView一样被渲染,所以类似与设置背景或者是重载drawRect方法都是没有任何效果的。
管理Subview
UIStackView
有两个属性
- arrangedSubviews
- subviews
如果我们想添加一个subview让StackView来管理,只要调用addArrangedSubview(_ view: UIView)
或者insertArrangedSubview(_ view: UIView, at stackIndex: Int)
即可,但是如果要删除一个被StackView管理的subview,那么我们需要主注意到removeArrangedSubview(_ view: UIView)
函数只是让对应的subview不让StackView来管理它的约束,它并没有从当前的视图层级从移除,如果要移除视图,我们需要显示调用removeFromSuperview()
。
简单的例子
参考