2

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")
        }
    }
}
pawello2222
  • 46,897
  • 22
  • 145
  • 209
hoshy
  • 481
  • 6
  • 15

1 Answers1

1

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")
            }
        }
    }
}
pawello2222
  • 46,897
  • 22
  • 145
  • 209
  • Thanks, but I tried that, but then they are right on top of each other and I would have to adjust their positions manually by applying offsets. I would like to keep the automatic vertical layouting of the VStack. – hoshy Aug 03 '20 at 12:19
  • @hoshy Then please share your code and describe the problem better - include other views as well as there is no problem when you have just two of them (as in the example above). – pawello2222 Aug 03 '20 at 12:26
  • Yes your solution works, but as explained, it also renders the VStack and Text on top of each other. So I would have to offset them to make them appear vertically structured. My question again would be if there is a way that the Spacer is the view shrinking and enlarging, keeping the HStack fixed. – hoshy Aug 03 '20 at 12:44
  • @hoshy See updated answer. Instead of `Text("top view")` you can place any other view (like `HStack`). – pawello2222 Aug 03 '20 at 12:46
  • Ah yes the two separate VStacks + Spacers did it. What a fiddle. Thanks man. – hoshy Aug 03 '20 at 12:50
  • 2
    Fun fact, with the two VStacks and internal Spacers you don't even need the ZStack, which makes the layout just perfect again. (This could be updated in your answer.) – hoshy Aug 03 '20 at 13:11