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

How to do it

  1. As usual, let's create a new Xcode project with Single View template and name it StackViews.
  2. Open the storyboard file and select the view controller and change its size to iPhone 4-inch.
  3. From Object Library, drag a Vertical stack view and add it as a subview.
  4. Change its frame to (X = 20, Y = 20, Width = 280).
  1. We need to add constraints to make the stack view's left, right, and top margins to be equal to 20 and to make its height = 75% of the device screen. To do so, first select the stack view, and click on the Pin button and set the top, left, and right constraint values to 20:

  1. For the height constraint, drag the stack view (while holding the Ctrl key) to the superview and click on Equal Heights:

  1. Now, the stack view height will be equal to the superview height, but we need it to be 75%. So, open, selecting the stack view. Open the Size Inspector tab and double-click on the height constraint. In the multiplier value, change it to 0.75:

  1. You will note that there is a warning in Xcode because your stack view's frame doesn't match the constraints. To solve it, just click on the warning indicator arrow, and then click on the warning indicator triangle that will show a popup asking how you want to fix the warning. Select Update frames from the options, and click on Fix Misplacement:

  1. Now, your stack view is ready. Let's add some content to it. From the Object Library, drag an image view and place it inside the stack view. You will note that the image view size automatically matches the stack view size.
  2. Repeat the previous process for two more image views. You will note that stack view automatically lays out the three image views to match the content.
  3. Now, select the stack view, click on Attribute Inspector, and change its setting to match the following screenshot:

  1. Now, set the images for image views to any images you have or use the ones we have in the resources folder for this chapter. You should have something like this:

  1. Now, build and run in simulator.