An iOS Stack View Tutorial

The previous chapter covered a lot of detail relating to the UIStackView class. This chapter will create an iOS app project that uses a wide range of features of the UIStackView class and the Interface Builder tool. At the end of this tutorial, topics such as stack view nesting, adding and removing subviews both within Interface Builder and in code, and the use of Auto Layout constraints to influence stack view layout behavior will have been covered.

About the Stack View Example App

The app created in this chapter is intended as an example of many ways the UIStackView class can be used to design a user interface. The example will consist of a single scene (Figure 32-1) containing multiple stack view instances that combine to create the screen for a coffee ordering app.

Figure 32-1

Creating the First Stack View

Create a new Xcode iOS project based on the App template named StackViewDemo.

The first stack view to create within the user interface layout is a vertical stack view containing two labels. Select the Main.storyboard file from the Project Navigator panel and click on the current View as: device setting in the bottom left-hand corner of the canvas to display the device configuration bar. Select an iPad configuration from the bar (the layout will still work on iPhone-size screens, but the iPad setting provides more room in the scene when designing the layout). Drag and drop two Labels from the Library panel onto the storyboard canvas and edit the text on each label so that the layout resembles that shown in Figure 32-2:

Figure 32-2

Select the uppermost label, display the Attributes Inspector panel and click on the T icon in the Font field to display the font selection menu. From within this menu, set the font for this label to Headline:

 

You are reading a sample chapter from Building iOS 17 Apps using Xcode Storyboards.

Buy the full book now in eBook or Print format.

The full book contains 96 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Figure 32-3

Finally, Shift-click on both labels and add them to a vertical stack view using the Embed In button in the lower right-hand corner of the storyboard canvas, as highlighted in Figure 32-4. From the resulting menu, select the Stack View option.

Figure 32-4

Once the button has been clicked, the two labels will be contained within a vertical stack view. Next, display the Document Outline panel, locate the newly inserted stack view from the hierarchy, select it, click on it a second time to enter editing mode, and change the name to “Title Stack View”. Naming stack views in this way makes it easier to understand the layout of the user interface as additional stack views are added to the design:

Figure 32-5

Creating the Banner Stack View

The top section of the storyboard scene will consist of a banner containing an image of a coffee cup and the Title Stack View created above. Begin by dragging and dropping an Image View object onto the scene and positioning and resizing it so that it resembles the layout in Figure 32-6:

Figure 32-6

With the Image View object selected, display the Attributes Inspector panel and change the Content Mode setting to Aspect Fit so that the image’s aspect ratio is retained when it is added to the view. From the source code, download the archive for the book and, using a Finder window, locate both the BlueCoffeeCup.png and RedCoffeeCup.png files in the stackview_images folder. Select the Assets entry in the Project Navigator panel and drag and drop the two image files beneath the AppIcon entry:

Figure 32-7

Display the Main.storyboard file again, select the image view, and use the Image property menu to select the BlueCoffeeCup image. Once selected, the image should appear within the storyboard scene.

 

You are reading a sample chapter from Building iOS 17 Apps using Xcode Storyboards.

Buy the full book now in eBook or Print format.

The full book contains 96 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Shift-click on both the Image View object and the Title Stack View objects in the scene so both are selected, and click the Embed In button once again to add both to a new horizontal stack view instance. Next, locate the new stack view in the Document Outline panel, select it, and click on it a second time. Once in editing mode, change the name to Banner Stack View.

With the Banner Stack View entry still selected in the Document Outline panel, display the Attributes Inspector panel and change the Alignment property to Center and the Distribution property to Fill Equally. This will ensure that the content is centered vertically within the stack view.

Figure 32-8

Adding the Switch Stack Views

The next stack views to create contain the two rows of Switch and Label objects. From the Library panel, drag four Label and four Switch objects onto the scene canvas so they are positioned beneath the Banner Stack View. Edit the text on the labels so that the views match those contained in Figure 32-9:

Figure 32-9

Use click and drag to select the first row of labels and switches so that all four views are selected. Add these views to a new horizontal stack view using the Embed In button at the bottom of the storyboard. Referring to the Document Outline panel, change the name of this stack view to “Switches 1 Stack View”. Repeat these steps to add the second row to a stack view named “Switches 2 Stack View”.

Select the Switches 1 Stack View in the Document Outline panel and change Alignment to Fill and Distribution to Equal Spacing using the Attributes Inspector panel. Repeat this step for the Switches 2 Stack View entry.

 

You are reading a sample chapter from Building iOS 17 Apps using Xcode Storyboards.

Buy the full book now in eBook or Print format.

The full book contains 96 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Creating the Top-Level Stack View

The next step is to add the existing stack views to a new vertical stack view. To achieve this, select the Banner

Stack View and the two Switch stack views in the storyboard scene and use the Embed In button to add them to a vertical stack. Then, locate this new parent stack view within the Document Outline panel and change the name to “Top Level Stack View.” At this point, verify that the view outline matches that of Figure 32-10:

Figure 32-10

With the Top Level Stack View object selected, change the Alignment and Distribution settings to Fill. With these changes made, the storyboard scene should appear as shown in Figure 32-11:

Figure 32-11

Adding the Button Stack View

Two Button objects now need to be added to the Top Level Stack View, but instead of using the Embed In button, this time, the stack view and buttons will be added directly to the top-level stack. With the Main.storyboard file selected, locate the Horizontal Stack View in the Library panel and drag it to the bottom edge of the Top Level Stack View in the storyboard scene so that a bold blue line appears together with a tag that reads “Top Level Stack View”:

Figure 32-12

Release the stack view to add it as a subview of the top-level stack, then use the Document Outline panel to name the stack “Button Stack View”. Next, drag and drop two Button views from the Library onto the new stack view. Next, select the Button Stack View entry in the Document Outline and change the Distribution property to Fill Equally. The buttons should now be spread equally over the width of the top-level stack view.

 

You are reading a sample chapter from Building iOS 17 Apps using Xcode Storyboards.

Buy the full book now in eBook or Print format.

The full book contains 96 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Double-click on the left button and change the text to read “Add a Cup”. Next, change the Background property in the View section of the Attributes Inspector panel to Custom, then change the Fill property to green. Next, repeat these steps for the right-hand button, setting the text to “Remove a Cup” and the background fill color cyan.

Display the Assistant Editor panel and establish action connections from the left and right buttons to methods named addCup and removeCup, respectively.

Adding the Final Subviews to the Top Level Stack View

Two final subviews now need to be added to the top-level stack view to complete the layout. First, drag a Date Picker object from the Library panel and drop it immediately above the Switches 1 Stack View in the Document Outline panel. Be sure to move the object toward the left so that the blue insertion line extends to the left-hand edge of the Switches 1 Stack View entry (highlighted in Figure 32-13) before dropping the view to ensure that it is added as a subview of the Top Level Stack View and not the banner or title stack views. Once the Date view has been added, select it and use the Attributes Inspector to change the Preferred Style property to Wheels:

Figure 32-13

Repeat the above step to insert a Horizontal Stack View immediately above the Button Stack View, pulling the dragged view to the left before dropping to add the view to the Top Level Stack View. Once added, name the stack view “Cup Stack View”.

With the Cup Stack View entry selected in the Outline Panel, display the Attributes Inspector panel and set the Alignment and Distribution properties to Center and Fill Equally, respectively.

 

You are reading a sample chapter from Building iOS 17 Apps using Xcode Storyboards.

Buy the full book now in eBook or Print format.

The full book contains 96 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Select the Top Level Stack View entry in the Document Outline panel and use the Auto Layout Add New Constraints menu to set Spacing to nearest neighbor constraints of 20 on all four edges of the view before clicking the Add 4 Constraints button:

Figure 32-14

At this point in the project, the layout of the storyboard scene should appear as illustrated in Figure 32-15:

Figure 32-15

Compile and run the app on a physical device or Simulator session and verify that the layout appears correctly.

Dynamically Adding and Removing Subviews

The final step is to add the code to the two action methods to add and remove the subviews within the Cups Stack View. Select this view in the storyboard scene, display the Assistant Editor, and establish an outlet connection named cupStackView.

Within the ViewController.swift file, implement the code within the addCup method as follows:

 

You are reading a sample chapter from Building iOS 17 Apps using Xcode Storyboards.

Buy the full book now in eBook or Print format.

The full book contains 96 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

@IBAction func addCup(_ sender: Any) {

    let cupImage = UIImageView(image: UIImage(named: "RedCoffeeCup"))
    cupImage.contentMode = .scaleAspectFit

    UIView.animate(withDuration: 0.75, animations: {
        self.cupStackView.addArrangedSubview(cupImage)
        self.cupStackView.layoutIfNeeded()
    })
}

The code begins by creating a new UIImageView object initialized with the red coffee cup image previously added to the asset catalog. This image view is then set to aspect fit mode so that the image will retain the original aspect ratio when displayed. An animation block is then used to animate the addition of the subview to the Cup Stack View instance.

The final step in this example is to add the code to remove the last coffee cup subview added to the stack within the removeCup method:

@IBAction func removeCup(_ sender: Any) {

    let lastAddedCup = self.cupStackView.arrangedSubviews.last

    if let cup = lastAddedCup
    {
        UIView.animate(withDuration: 0.25, animations: {
            self.cupStackView.removeArrangedSubview(cup)
            cup.removeFromSuperview()
            self.cupStackView.layoutIfNeeded()
        })
    }
}

This method accesses the arrangedSubviews array of the stack view to obtain the last added subview. This subview is then removed both from the arrangedSubviews array and the subviews of the parent view, all from within an animation block.

Compile and run the app and test that the buttons now add and remove coffee cup subviews and that the changes are animated.

Summary

This chapter has worked through the creation of an example app that makes use of the UIStackView class. The tutorial demonstrated the use of horizontal and vertical stack views, stack view nesting, the addition of subviews to a stack in Interface Builder both manually and using the Stack button, and the dynamic addition and removal of subviews from within code. The example also demonstrated the use of compression priority settings to finetune the layout behavior of a stack view.

 

You are reading a sample chapter from Building iOS 17 Apps using Xcode Storyboards.

Buy the full book now in eBook or Print format.

The full book contains 96 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 


Categories