iOS Programming Cookbook
上QQ阅读APP看书,第一时间看更新

How it works...

As we saw in the preceding section, it's easy to manage and work with stack views. Let's take a look at how the preceding example works:

  1. We started by placing a vertical UIStackView from Object library in our view hierarchy and set its Auto Layout to define its position and size. As we said, you don't have to set any Auto Layout for the subviews of the stack view, but you have to set Auto Layout for the stack view itself.
  2. We selected three image views from the Object Library, and noted how awesome the stack view is while it automatically lay out the image views to fill the content.
  3. From Attribute Inspector, we set some settings to the stack view, which will highlight the most important ones, such as the following:
    • Axis: You choose whether you want the stack to layout your subview vertically or horizontally. For example, in horizontal layout, you will note that the first item leading edge will be pinned to the stack's leading edge, and the last item trailing edge will be pinned to the stack's trailing edge. In vertical layout, the layout will be arranged based on top and bottom edges.
    • Alignment: This option indicates how the stack view will align your subview relative to the stack view. For example, when you set it to Center when the Axis is vertical, stack view will calculate the size of each item and center it horizontally. However, when you set it to Leading, all items will be aligned along with the stack view's leading. In our example, we set it to Fill, which means the stack view will stretch the arranged views to match the stack view.
    • Distribution: The option defines the size of the arranged views. For example, when you set it to Fill Equally, the stack view will lay them out, so all arranged views share the same size.
    • Spacing: This defines the spacing between the arranged views.
  4. When you run the app in different screen size, you will see the magic in how stack views lays out your images equally so that it fits the screen size of the simulator or device.