Search code examples
iosswiftswiftuiswiftui-layout

How to ignore parent view's padding SwiftUI


I have a VStack with multiple child views (the one with blue background). The VStack has horizontal padding. I want to have this padding set for each child, but sometimes I have exception where I want that child to reach edges of the display completely (Two grey lines above "Checkout" button). Is there any way how to allow this to happen? I don't wanna set padding for every single child separately.


Solution

  • You can apply a negative padding on the view that you applied on the VStack, that means if you applied a padding of 16 points to the VStack like this for example .padding(16) for all directions which is the default. then you can apply a .padding(.horizontal,-16) to the lines and they will stretch to the end of the screen

    here is a sample code and a screenshot for the behavior you want. Screenshot

    struct VStackPadding: View {
        var body: some View {
            VStack{
                RoundedRectangle(cornerRadius: 4)
                    .frame(width: .infinity,height: 3)
                    .padding(.horizontal, -16)
                    .padding(.bottom,16)
                
                RoundedRectangle(cornerRadius: 4)
                    .frame(width: .infinity,height: 3)
            }.padding(16)
        }
    }