Horizontal Stack

Last updated on 20 Oct 2024.

Written by Jia Chen.

Swift Playgrounds for iPad app icon

Sample Project

Horizontal Stack

Last updated on 20 Oct 2024.

Written by Jia Chen.

Swift Playgrounds for iPad app icon

Sample Project

Horizontal Stack

Last updated on 20 Oct 2024.

Written by Jia Chen.

Swift Playgrounds for iPad app icon

Sample Project

Scroll Down

On this page

On this page

Creating a Horizontal Stack

A HStack allows you to arrange subviews horizontally.

struct ContentView: View {
    var body: some View {
        HStack {
            Text("🍎")
            Text("🍌")
            Text("🍅")
        }
    }
}

Customizing Spacing

Use the spacing parameter to set a custom spacing between subviews of a HStack.

HStack(spacing: 32) {
    Text("🍎")
    Text("🍌")
    Text("🍅")
}

Customizing Alignment

By default, the HStack's alignment is set to the center. You can set the alignment of subviews in a HStack to top, center, or bottom.

HStack(alignment: .top) {
    Text("hello")
    Image(.globe)
    Text("world")
}
HStack(alignment: .center) {
    Text("hello")
    Image(.globe)
    Text("world")
}


HStack(alignment: .bottom) {
    Text("hello")
    Image(.globe)
    Text("world")
}

Combined with Vertical Stack

You can nest a HStack into a VStack and vice-versa as they are all views. This allows you to create more complex layouts.

HStack {
    VStack {
        Text("🍎")
        Text("🍌")
    }
    VStack {
        Text("🍋")
        Text("🍅")
    }
}

© 2024 Tinkertanker Pte Ltd / Swift Accelerator. All rights reserved.

© 2024 Tinkertanker Pte Ltd / Swift Accelerator. All rights reserved.

© 2024 Tinkertanker Pte Ltd / Swift Accelerator. All rights reserved.