swiftui

VStack spacing issue after .trailing


I still have some space after the trailing. here is the code

VStack(alignment: .trailing) {
                
                
                Text("History & Text")
                    .font(.title)
                    .foregroundStyle(.secondary)
                
                Text(currentDisplay)
                    .font(.largeTitle)
                    .foregroundStyle(.white)
                    .padding()
            }
            .frame(maxWidth: .infinity)

enter image description here

How do I get rid of the space at the end.


Solution

  • The VStack is indeed aligning its views on the trailing side, but the VStack itself is not wide enough to fill the whole width of the screen.

    .frame(maxWidth: .infinity) does not change the VStack. It simply puts the VStack inside an "invisible frame" that fills the width of the screen. How is the VStack aligned inside this frame? From the documentation, we can see that the default value of the alignment: parameter is .center.

    If you pass alignment: .trailing, the VStack will be aligned to the trailing edge of the invisible frame that fills the width of the screen.

    VStack(alignment: .trailing) {
        Text("History & Text")
            .font(.title)
            .foregroundStyle(.secondary)
        
        Text(currentDisplay)
            .font(.largeTitle)
            .foregroundStyle(.white)
            .padding()
    }
    .frame(maxWidth: .infinity, alignment: .trailing)