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

How to Use VStack in SwiftUI: Syntax and Examples

In SwiftUI, use VStack to arrange views vertically in a column. You place child views inside VStack braces, and you can customize spacing and alignment easily.
๐Ÿ“

Syntax

The VStack is a container that stacks child views vertically. You can specify optional parameters like alignment to align views horizontally and spacing to set space between views.

  • alignment: Aligns views horizontally (e.g., .leading, .center, .trailing).
  • spacing: Sets vertical space between views (default is system spacing).
  • Inside the braces, add the views you want stacked vertically.
swift
VStack(alignment: .center, spacing: 10) {
    Text("First")
    Text("Second")
    Text("Third")
}
Output
Three text labels stacked vertically with 10 points space between them, centered horizontally.
๐Ÿ’ป

Example

This example shows a simple VStack with three text views stacked vertically, aligned to the leading edge with 15 points spacing.

swift
import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack(alignment: .leading, spacing: 15) {
            Text("Hello")
                .font(.title)
            Text("Welcome to VStack")
                .foregroundColor(.gray)
            Text("Enjoy SwiftUI!")
                .bold()
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
Output
A vertical stack of three text lines: "Hello" (large font), "Welcome to VStack" (gray color), and "Enjoy SwiftUI!" (bold), aligned left with spacing and padding.
โš ๏ธ

Common Pitfalls

Common mistakes when using VStack include:

  • Not specifying alignment when needed, causing unexpected horizontal alignment.
  • Forgetting to add spacing, which can make views look cramped.
  • Placing too many views without scrolling, which can overflow the screen.

Always consider adding ScrollView if content might be long.

swift
/* Wrong: No spacing, default center alignment */
VStack {
    Text("One")
    Text("Two")
    Text("Three")
}

/* Right: Added spacing and leading alignment */
VStack(alignment: .leading, spacing: 12) {
    Text("One")
    Text("Two")
    Text("Three")
}
Output
Wrong: Texts stacked tightly and centered horizontally. Right: Texts spaced by 12 points and aligned to the left.
๐Ÿ“Š

Quick Reference

Use this quick guide when working with VStack:

  • alignment: .leading, .center, .trailing
  • spacing: CGFloat value for vertical gaps
  • Wrap many views in ScrollView to avoid clipping
  • Combine with HStack and ZStack for complex layouts
โœ…

Key Takeaways

Use VStack to stack views vertically in SwiftUI with customizable alignment and spacing.
Always specify alignment and spacing to control layout appearance clearly.
Wrap VStack in ScrollView if content might exceed screen height.
Combine VStack with other stacks for flexible UI designs.