Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
SwiftUI Cookbook

You're reading from   SwiftUI Cookbook A guide for building beautiful and interactive SwiftUI apps

Arrow left icon
Product type Paperback
Published in Dec 2023
Publisher Packt
ISBN-13 9781805121732
Length 798 pages
Edition 3rd Edition
Languages
Tools
Concepts
Arrow right icon
Author (1):
Arrow left icon
Juan C. Catalan Juan C. Catalan
Author Profile Icon Juan C. Catalan
Juan C. Catalan
Arrow right icon
View More author details
Toc

Table of Contents (20) Chapters Close

Preface 1. Using the Basic SwiftUI Views and Controls FREE CHAPTER 2. Displaying Scrollable Content with Lists and Scroll Views 3. Exploring Advanced Components 4. Viewing while Building with SwiftUI Preview in Xcode 15 5. Creating New Components and Grouping Views with Container Views 6. Presenting Views Modally 7. Navigation Containers 8. Drawing with SwiftUI 9. Animating with SwiftUI 10. Driving SwiftUI with Data 11. Driving SwiftUI with Combine 12. SwiftUI Concurrency with async await 13. Handling Authentication and Firebase with SwiftUI 14. Persistence in SwiftUI with Core Data and SwiftData 15. Data Visualization with Swift Charts 16. Creating Multiplatform Apps with SwiftUI 17. SwiftUI Tips and Tricks 18. Other Books You May Enjoy
19. Index

Laying out components

In this very first recipe of the book, we will start laying out components. In SwiftUI, our user interface is composed of different elements. It is very important to understand how to group components together in different layouts. SwiftUI uses three basic layout components, VStack, HStack, and ZStack. Use the VStack view to arrange components on a vertical axis, HStack to arrange components on a horizontal axis, and—you guessed it right—use the ZStack to arrange components along the vertical and horizontal axis.

In this recipe, we will also look at spacing and adjust the position used to position elements. We will also look at how Spacer and Divider can be used for layout.

Getting ready

Let’s start by creating a new SwiftUI project called TheStacks. Use the following steps:

  1. Start Xcode (Finder | Applications | Xcode).
  2. Click on Create a new Xcode project from the left pane.
  3. The following screen asks us to choose an Xcode template. Select iOS, and then App. Click Next.
  4. A screen to select the options for the project will appear. Enter the product name, TheStacks.
  5. Make sure that Interface is set to SwiftUI, Language is set to Swift, and Storage is set to None. Click Next.
  6. Select the folder location to store the project and choose if you want to create a Git repository or not. Then click Create.

How to do it…

Let’s implement the VStack, HStack, and ZStack within a single screen to better understand how each works and the differences between them. The steps are given here:

  1. Select the Contentview/Contentview.swift file on the navigation pane (left side of Xcode).
  2. Replace the content of the body variable with a VStack and some Text views:
        var body: some View {
            VStack {
                Text("VStack Item 1")
                Text("VStack Item 2")
                Text("VStack Item 3")
            }
            .background(.blue)
        }
    
  3. Press Cmd + Option + Enter if the canvas is not visible, then click on the Resume button above the canvas window to display the resulting view:

Figure 1.1: VStack with three items

  1. Add a Spacer and a Divider between VStack Item 2 and VStack Item 3:
    Spacer()
    Divider()
       .background(.black)
    
  2. The content expands and covers the screen’s width and height, as follows:

Figure 1.2: VStack + Spacer + Divider

  1. Add an HStack and a ZStack below VStack Item 3:
    HStack{
       Text("HStack Item 1")
       Divider()
           .background(.black)
       Text("HStack Item 2")
       Divider()
            .background(.black)
       Spacer()
       Text("HStack Item 3")
    }
    .background(Color.red)
    ZStack{
       Text("ZStack Item 1")
           .padding()
           .background(.green)
           .opacity(0.8)
       Text("ZStack Item 2")
           .padding()
           .background(.green)
           .offset(x: 80, y: -400)
    }
    
  2. The preview should look like the following screenshot (it may vary depending on the device selected for previews):

Figure 1.3: VStack, HStack, and ZStack

This concludes our recipe on using stacks. Going forward, we’ll make extensive use of VStack and HStack to position various components in our views.

How it works…

In Xcode 15, a new iOS app project with SwiftUI selected as the interface option starts with a VStack that includes an Image view and a Text view located at the center of the screen. We replaced the content provided by the template with our own VStack, with three embedded Text views. SwiftUI container views like VStack determine how to display content by using the following steps:

  1. Figure out its internal spacing and subtract that from the size proposed by its parent view.
  2. Divide the remaining space into equal parts.
  3. Process the size of its least flexible view.
  4. Divide the remaining unclaimed space by the unallocated space, and then repeat Step 2.
  5. The stack then aligns its content and chooses its own size to exactly enclose its children.

Adding the Spacer() forces the view to use the maximum amount of vertical space. This is because the Spacer() is the most flexible view—it fills the remaining space after all other views have been displayed.

The Divider() component is used to draw a horizontal line across the width of its parent view. That is why adding a Divider() view stretched the VStack background from just around the Text views to the entire width of the VStack. By default, the divider line does not have a color. To set the divider color, we add the .background(.black) modifier. Modifiers are methods that can be applied to a view to return a new view. In other words, it applies changes to a view. Examples include .background(.black), .padding(), and .offset(…).

The HStack container is like the VStack but its contents are displayed horizontally from left to right. Adding a Spacer() in an HStack thus causes it to fill all available horizontal space, and a divider draws a vertical line between components in the HStack.

The ZStack is like HStack and VStack but overlays its content on top of existing items.

There’s more…

You can also use the .frame modifier to adjust the width and height of a component. Try deleting the Spacer() and Divider() from the HStack and then apply the following modifier to the HStack:

.frame(
    maxWidth: .infinity,
    maxHeight: .infinity,
    alignment: .topLeading
)
You have been reading a chapter from
SwiftUI Cookbook - Third Edition
Published in: Dec 2023
Publisher: Packt
ISBN-13: 9781805121732
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.
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 $19.99/month. Cancel anytime
Banner background image