Reader small image

You're reading from  SwiftUI Essentials – iOS 14 Edition

Product typeBook
Published inMay 2021
Reading LevelBeginner
PublisherPackt
ISBN-139781801813228
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Neil Smyth
Neil Smyth
author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth

Right arrow

27. SwiftUI Stack Alignment and Alignment Guides

The chapter entitled “SwiftUI Stacks and Frames” touched on the basics of alignment in the context of stack container views. Inevitably, when it comes to designing complex user interface layouts, it will be necessary to move beyond the standard alignment options provided with SwiftUI stack views. With this in mind, this chapter will introduce more advanced stack alignment techniques including container alignment, alignment guides, custom alignments and the implementation of alignments between different stacks.

27.1 Container Alignment

The most basic of alignment options when working with SwiftUI stacks is container alignment. These settings define how the child views contained within a stack are aligned in relation to each other and the containing stack. This alignment value applies to all the contained child views unless different alignment guides have been applied on individual views. Views that do not have their own alignment guide are said to be implicitly aligned.

When working with alignments it is important to remember that horizontal stacks (HStack) align child views vertically, while vertical stacks (VStack) align their children horizontally. In the case of the ZStack, both horizontal and vertical alignment values are used.

The following VStack declaration consists of a simple VStack configuration containing three child views:

VStack {

    Text("This is some text")

    Text("This is some longer text")

...

27.2 Alignment Guides

An alignment guide is used to define a custom position within a view that is to be used when that view is aligned with other views contained in a stack. This allows more complex alignments to be implemented than those offered by the standard alignment types such as center, leading and top, though these standard types may still be used when defining an alignment guide. An alignment guide could, for example, be used to align a view based on a position two thirds along its length or 20 points from the top edge.

Alignment guides are applied to views using the alignmentGuide() modifier which takes as arguments a standard alignment type and a closure which must calculate and return a value indicating the point within the view on which the alignment is to be based. To assist in calculating the alignment position within the view, the closure is passed a ViewDimensions object which can be used to obtain the width and height of the view and also the view’s standard...

27.3 Using the Alignment Guides Tool

The best way to gain familiarity with alignment guides is to experiment with the various settings and options. Fortunately, the SwiftUI Lab has created a useful learning tool for trying out the various alignment settings. To use the tool, begin by creating a new Xcode SwiftUI project named AlignmentTool, open the ContentView.swift file and remove all the existing contents.

Next, open a web browser and navigate to the following URL:

http://bit.ly/2MCioyl

This page contains the source code for a tool in a file named alignment-guides-tool.swift. Select and copy the entire source code from the file and paste it into the ContentView.swift file in Xcode. Once loaded, compile and run the app on an iPad device or simulator in landscape mode where it will appear as shown in Figure 27-10:

Figure 27-10

Turn on the Include Implicitly View option to see what a view will do without any alignment guides and use the yellow bars under each view...

27.4 Custom Alignment Types

In the previous examples, changes have been made to view alignments based on the standard alignment types. SwiftUI provides a way for the set of standard types to be extended by declaring custom alignment types. A custom alignment type named oneThird could, for example, be created which would make the point of alignment one third of the distance from a specified edge of a view.

Take, for example, the following HStack configuration consisting of four rectangles centered vertically:

Figure 27-11

The declaration to display the above layout reads as follows:

HStack(alignment: .center) {

      Rectangle()

          .foregroundColor(Color.green)

          .frame(width: 50, height: 200)

      Rectangle()

          .foregroundColor...

27.5 Cross Stack Alignment

A typical user interface layout will be created by nesting stacks to multiple levels. A key shortcoming of the standard alignment types is that they do not provide a way for a view in one stack to be aligned with a view in another stack. Consider the following stack configuration consisting of a VStack embedded inside an HStack. In addition to the embedded VStack, the HStack also contains a single additional view:

Figure 27-14

The corresponding declaration for the above nested layout reads as follows:

HStack(alignment: .center, spacing: 20) {

    

    Circle()

        .foregroundColor(Color.purple)

        .frame(width: 100, height: 100)

    

    VStack(alignment: .center) {

        Rectangle()

     ...

27.6 ZStack Custom Alignment

By default, the child views of a ZStack are overlaid on top of each other and center aligned. The following figure shows three shape views (circle, square and capsule) stacked on top of each other in a ZStack and center aligned:

Figure 27-16

Using the standard alignment types, the alignment of all the embedded views can be changed. In Figure 27-17 for example, the ZStack has .leading alignment configured:

Figure 27-17

To perform more advanced alignment layouts, where each view within the stack has its own alignment, both horizontal and vertical custom alignments must be combined into a single custom alignment, for example:

extension HorizontalAlignment {

    enum MyHorizontal: AlignmentID {

        static func defaultValue(in d: ViewDimensions) -> CGFloat

                 { d...

27.7 Summary

The SwiftUI stack container views can be configured using basic alignment settings that control the positioning of all child views relative to the container. Alignment of individual views within a stack may be configured using alignment guides. An alignment guide includes a closure which is passed a ViewDimensions object which can be used to compute the alignment position for the view based on the view’s height and width. These alignment guides can be implemented as custom alignments which can be reused in the same way as standard alignments when declaring a stack view layout. Custom alignments are also a useful tool when views contained in different stacks need to be aligned with each other. Custom alignment of ZStack child views requires both horizontal and vertical alignment guides.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
SwiftUI Essentials – iOS 14 Edition
Published in: May 2021Publisher: PacktISBN-13: 9781801813228
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Author (1)

author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth