Overview
This chapter introduces Stacks, your main tool for organizing elements on a view. You had a brief preview of how Stacks work in our first lesson. However, in this chapter, Ng unpacks the details behind Horizontal Stacks (HStack), Vertical Stacks (VStack), and three-dimensional stacks (ZStacks). In this chapter, you will also learn how to “extract subviews,” as a way to keep your code more organized and tidy.
As with the previous lessons, these are fundamental concepts that will help serve as the foundation for the rest of your app dev journey. Be sure you have a thorough understanding of these concepts before proceeding onward.
Lastly, you’ll see that Chapter 4 includes a couple of exercises in the text book. While you’re not required to submit anything for these exercises, I heavily encourage you to complete them. Learning by doing is undoubtedly the best way to learn application and absorb the material we’re covering. Therefore, the more practice to apply and test your knowledge, the better!
Read Chapter 4: Layout User Interfaces with Stacks in Mastering SwiftUI
Key Takeaways
- HStack arranges views horizontally, VStack arranges them vertically, and ZStack layers them along the depth axis — these three are the backbone of every SwiftUI layout.
Spacer()pushes adjacent views apart by filling all available space in the current stack direction.- Stacks are freely nestable and composable — complex layouts are built from stacks inside stacks.
- “Extracting subviews” moves a block of view code into its own named struct, keeping
ContentViewreadable and your code organized. - Complete every in-chapter exercise — Stacks are the foundation that all future lessons build on.