0

I have 5 VStacks in an HStack that spans the width of the screen. The VStack contains Text Views that are all different widths because they display different text. What I want to do is align the center of each VStack so that they are evenly apart from each other and the edges of the screen. I know the width of the screen (I used GeometryReader) and I am pretty sure that to get the x value of each VStack I need to divide the width of the screen by 6, and that the center of each VStack should fall on the width of the screen divided by 6 and then multiplied by the number that represents its position in the HStack (so the first VStack at the top of the HStack would be 1). Since all of the VStacks have different widths I don't think I can use the spacing argument in the HStack to accomplish this. Thus I need a way to align the center of each VStack equally so that there is an even space between each of them and the edge of the screen.

Here is my code:

HStack() {
        VStack(spacing: 10){
            Text("123")
                .foregroundColor(Color.white)
            Text("Value 1")
                .foregroundColor(Color.gray)
        }
        

        VStack(spacing: 10){
            Text("6534675")
                .foregroundColor(Color.white)
            Text("Value 23")
                .foregroundColor(Color.gray)
        }
        
        VStack(spacing: 10){
            Text("6534")
                .foregroundColor(Color.white)
            Text("Value 203")
                .foregroundColor(Color.gray)
        }
        
        VStack(spacing: 10){
            Text("1055")
                .foregroundColor(Color.white)
            Text("Value 4589")
                .foregroundColor(Color.gray)
        }
        
        VStack(spacing: 10){
            Text("4")
                .foregroundColor(Color.white)
            Text("Value 5")
                .foregroundColor(Color.gray)
        }
        
    }.frame(width: geo.size.width)
coder
  • 381
  • 2
  • 22
  • Not sure I understood what do you mean. The provided code even on iPhone 11 Pro Max fills screen tightly, making dynamic text a bit larger and layout looks bad, because of wrapped text. On SE it will be rather bad from default. So what's to goal? Sketch? Screenshot? – Asperi Aug 07 '20 at 04:37

2 Answers2

0

If you know the width of the VStacks, you can work with .padding()

Syntax Example:

VStack(spacing: 10){
        Text("4")
            .foregroundColor(Color.white)
        Text("Value 5")
            .foregroundColor(Color.gray)
    }.padding(10)
Vubito32
  • 48
  • 6
  • Unfortunately, I do not know the width of the VStacks, and the values in the text view are meant to be dynamic so I would constantly need to change the padding. – coder Aug 07 '20 at 00:40
0

Can use .position() to position the center of the view.

Detailed Documentation: https://developer.apple.com/documentation/swiftui/vstack-view-modifiers

Vubito32
  • 48
  • 6