Home > OS >  How to align properly with GeometryReader in SwiftUI
How to align properly with GeometryReader in SwiftUI

Time:05-05

So I am making an app and I had a problem with GeometryReader. I created a test file and cannot figure out what I a doing wrong. I am trying to align all Text views to leading. However only two of them actually move. I have a VStack embedded in a VStack and I think that is where the problem is.

struct TestFile: View {
    var body: some View {
        
        HStack {
            Text("Hello")
            GeometryReader { geo in
                VStack(alignment: .leading) {
                    Text("Test 1")
                    Text("Test 2")
                    
                    VStack {
                        Text("Test 3")
                        Text("Test 4")
                    }
                    .frame(width: geo.size.width)

                }
                .background(.orange)
            }
            .background(.purple)
            
            
        }
        .background(.green)
        
        
        

    }
}

struct TestFile_Previews: PreviewProvider {
    static var previews: some View {
        TestFile()
    }
}

This is what happens

enter image description here

How can I also get Test 3 and Test 4 to the same alignment as Test 1 and Test 2? I've tried placing alignments on both VStacks and that does nothing unfortunately.

CodePudding user response:

You don't need GeometryReader for that, but use alignment, like

VStack {
    Text("Test 3")
    Text("Test 4")
}
.frame(maxWidth: .infinity, alignment: .leading)  // << here !!

and get rid of unused GR.

  • Related