0
0
iOS Swiftmobile~5 mins

VStack, HStack, ZStack in iOS Swift

Choose your learning style9 modes available
Introduction

Stacks help you arrange views easily in a line or on top of each other. They make your app look neat without much work.

To put buttons or text one below another in a column.
To place images or icons side by side in a row.
To layer views on top of each other, like putting a label over a picture.
To create simple layouts that adjust well on different screen sizes.
To group related views together visually.
Syntax
iOS Swift
VStack {
    // views stacked vertically
}

HStack {
    // views stacked horizontally
}

ZStack {
    // views stacked on top of each other
}

Use VStack for vertical layout, HStack for horizontal layout, and ZStack to overlap views.

You can add spacing and alignment options inside the stacks.

Examples
This puts two text views one below the other.
iOS Swift
VStack {
    Text("Hello")
    Text("World")
}
This places two icons side by side with space between them.
iOS Swift
HStack(spacing: 20) {
    Image(systemName: "star")
    Image(systemName: "heart")
}
This draws a blue circle with the text "Hi" on top.
iOS Swift
ZStack {
    Circle().fill(Color.blue).frame(width: 100, height: 100)
    Text("Hi")
}
Vertical stack with left alignment and space between texts.
iOS Swift
VStack(alignment: .leading, spacing: 10) {
    Text("Left aligned")
    Text("Texts")
}
Sample App

This app shows three stacks: a vertical stack with three texts, a horizontal stack with three texts, and a ZStack with a green square and text on top.

iOS Swift
import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack(spacing: 30) {
            Text("VStack Example")
                .font(.headline)

            VStack {
                Text("One")
                Text("Two")
                Text("Three")
            }
            .border(Color.gray)

            HStack(spacing: 20) {
                Text("A")
                Text("B")
                Text("C")
            }
            .border(Color.blue)

            ZStack {
                Rectangle()
                    .fill(Color.green)
                    .frame(width: 100, height: 100)
                Text("On Top")
                    .foregroundColor(.white)
                    .bold()
            }
        }
        .padding()
    }
}

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
OutputSuccess
Important Notes

Stacks automatically adjust to screen size and orientation.

You can nest stacks inside each other for complex layouts.

Use alignment and spacing parameters to control layout details.

Summary

VStack arranges views vertically.

HStack arranges views horizontally.

ZStack layers views on top of each other.