How to remove padding in the ZStack SwiftUI

Viewed 2942

I'm getting weird padding when trying to put another VStack in ZStack. How to remove it?

struct ContentView: View {
var body: some View {
    VStack{
        VStack{
            Text("1")
        }
        .frame(width: 200, height: 50)
        .background(Color.init(.green))

        ZStack{
            VStack{
                Text("2")
            }
            .frame(width: 210, height: 50)
            .background(Color.init(.blue))
            VStack{
                Text("3")
            }
            .frame(width: 200, height: 50)
            .background(Color.init(.green))
        }

        VStack{
            Text("4")
        }
        .frame(width: 200, height: 50)
        .background(Color.init(.green))
    }    
}

}

if I comment VStack with Text("2"), padding will disappear.

Screenshot of weird padding

2 Answers

Here it is

var body: some View {
    VStack(spacing: 0) { // << here !!

You have provide different width in

VStack{
      Text("2")
}
.frame(width: 210, height: 50)
.background(Color.init(.blue))

the width is 210 and other element width is 200 provide the same width the padding will remove.

Related