0
0
Ios-swiftHow-ToBeginner ยท 3 min read

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: alignment aligns views vertically inside the horizontal stack, not horizontally.
  • Forgetting to add .frame or 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

PropertyDescriptionExample Values
alignmentVertical alignment of child views.top, .center, .bottom
spacingSpace between child views in points8, 10, 20
contentChild views arranged horizontallyText, 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.