We’ll explore three essential building blocks of layouts in SwiftUI: Stacks, Frames, and Alignment. By the end of this blog, you’ll be able to craft pixel-perfect UIs for any screen size.
How SwiftUI Handles Layout
- Parent Views propose a size to their child views.
- Child Views decide their size and return it to the parent.
With this foundation, let’s dive into the tools SwiftUI offers for creating layouts.
Stacks: The Foundation of SwiftUI Layouts
An HStack arranges views in a horizontal line:
- spacing: Adjusts the space between views.
- alignment: Aligns views along a vertical axis.
A VStack arranges views in a vertical line:
Align views horizontally using the alignment parameter.
A ZStack overlays views on top of each other:
Use alignment to position views within the stack.
Frames: Controlling Size and Position
- Set Fixed Dimensions:
- Expand to Fill Parent:
The alignment parameter controls how the content is positioned inside the frame:
For advanced control, SwiftUI provides alignment guides, allowing fine-grained positioning of views.
Let’s put everything together to create a Profile Card UI:
Key Takeaways
- Stacks are the foundation of layouts in SwiftUI: HStack, VStack, and ZStack.
- Use frames to control size and positioning.
- Alignment guides give fine-grained control over view positioning.
By mastering these tools, you can build sophisticated and responsive layouts in SwiftUI.