How to Use HStack in SwiftUI: Simple Horizontal Layout
In SwiftUI, use
HStack to arrange views horizontally in a row. You place child views inside HStack and it automatically lays them out side by side with optional spacing and alignment.Syntax
The HStack is a container view that arranges its child views horizontally. You can specify optional alignment and spacing parameters.
alignment: Aligns views vertically (e.g.,.top,.center,.bottom).spacing: Sets space between views in points.
swift
HStack(alignment: .center, spacing: 10) { Text("First") Text("Second") Text("Third") }
Output
A horizontal row showing the texts: First, Second, Third spaced by 10 points and vertically centered.
Example
This example shows three colored squares arranged horizontally with spacing and bottom alignment.
swift
import SwiftUI struct ContentView: View { var body: some View { HStack(alignment: .bottom, spacing: 20) { Rectangle() .fill(Color.red) .frame(width: 50, height: 50) Rectangle() .fill(Color.green) .frame(width: 50, height: 100) Rectangle() .fill(Color.blue) .frame(width: 50, height: 75) } .padding() } }
Output
Three colored rectangles arranged side by side horizontally with 20 points spacing, aligned at their bottom edges.
Common Pitfalls
Common mistakes when using HStack include:
- Not specifying spacing, which can cause views to be too close.
- Misunderstanding alignment:
alignmentaligns views vertically inside the horizontal stack, not horizontally. - Forgetting to add
.frameor size modifiers, which can cause views to collapse or stretch unexpectedly.
swift
/* Wrong: No spacing, views too close */ HStack { Text("A") Text("B") } /* Right: Add spacing for clarity */ HStack(spacing: 15) { Text("A") Text("B") }
Output
First snippet shows texts 'A' and 'B' very close; second snippet shows them spaced by 15 points.
Quick Reference
| Property | Description | Example Values |
|---|---|---|
| alignment | Vertical alignment of child views | .top, .center, .bottom |
| spacing | Space between child views in points | 8, 10, 20 |
| content | Child views arranged horizontally | Text, Image, Rectangle |
Key Takeaways
Use HStack to arrange views horizontally in SwiftUI.
Set spacing to control the gap between views inside HStack.
Alignment in HStack controls vertical alignment of child views.
Always add size modifiers to views to avoid unexpected layout.
HStack automatically sizes to fit its content horizontally.