Spacer

Last updated on 20 Oct 2024.

Written by Jia Chen.

Spacer

Last updated on 20 Oct 2024.

Written by Jia Chen.

Spacer

Last updated on 20 Oct 2024.

Written by Jia Chen.

Scroll Down

On this page

On this page

Creating a Spacer

A Spacer is used to add a flexible space between subviews in a stack view like a VStack or HStack.

Spacer in Horizontal Stacks

When in a HStack, it spreads the elements apart horizontally.

struct ContentView: View {
    var body: some View {
        HStack {
            Text("social")
            Spacer()
            Text("distanced")
        }
    }
}

This can also be used to align elements together to the leading or trailing edge.

struct ContentView: View {
    var body: some View {
        HStack {
            Image(systemName: "hand.wave")
            Text("hello")
            Spacer()
        }
    }
}


struct ContentView: View {
    var body: some View {
        HStack {
            Spacer()
            Image(systemName: "hand.wave")
            Text("hello, again")
        }
    }
}

Spacer in Vertical Stacks

When in a VStack, the Spacer spreads elements apart vertically.

struct ContentView: View {
    var body: some View {
        VStack {
            Text("up high")
            Spacer()
            Text("down low")
        }
    }
}


This can also be used to align to the top and bottom edges of the parent view.

struct ContentView: View {
    var body: some View {
        VStack {
            Image(systemName: "hand.wave")
            Text("hello from up here!")
            Spacer()
        }
    }
}


struct ContentView: View {
    var body: some View {
        VStack {
            Spacer()
            Text("😢")
            Text("oh i fell down.")
        }
    }
}

Using Multiple Spacers

You can also use multiple spacers to set different distances.

In the following example, the gap between the 🍎 and 🍋 is twice that of the gap between 🍌 and 🍎.

HStack {
    Text("🍌")
    Spacer()
    Text("🍎")
    Spacer()
    Spacer()
    Text("🍋")
}

Setting a Minimum Length

You can also specify a minimum length for a Spacer, ensuring the Spacer does not fall below a certain size.

Spacer(minLength: 32)

© 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.