SwiftUI VStack with flexible Spacer

Viewed 1613

I have a simple VStack with a view on top and a multiline Text in the bottom. The text can update its content, so it resizes depending on how many lines it has. When that happens, the view on top adjusts its position as well - moving up or down.

I want the top view to keep having a fixed vertical position, independent of the views below in the VStack. To my thinking this is what Spacer are for, since they are flexible. Yet this doesn't to the trick.

struct ContentView: View {
    var body: some View {
        VStack {
            HStack("Some Icons")
            Spacer()
            Text("Multiline Text")
        }
    }
}
1 Answers

You may wrap it in a ZStack:

struct ContentView: View {
    var body: some View {
        ZStack {
            VStack {
                Text("top view")
                Spacer()
            }
            VStack {
                Spacer()
                Text("bottom view")
            }
        }
    }
}

This way everything in the first VStack will not move in relation to the second VStack.


Alternatively you can continue using a VStack but wrap its subviews in the separate VStacks:

struct ContentView: View {
    var body: some View {
        VStack {
            VStack {
                Text("top view")
                Spacer()
            }
            VStack {
                Spacer()
                Text("bottom view")
            }
        }
    }
}
Related