The SwiftUI Field Guidebeta

Padding

The padding modifier adds padding to a view. It does so by taking the proposed size and subtracting the padding. Likewise, it adds padding to the reported size of its child. When we don't specify additional parameters, the default system padding (16 on this website) is used, and it's applied to all edges.

Code
Color.blue    .padding()
Preview
200

We can also specify an explicit value for the padding:

Code
Color.blue    .padding(
)
Preview
200

Sometimes, negative padding can be useful to break out of the bounds of a view. In the example below, the background gets proposed the size of the text, but the negative padding makes sure the green rectangle is larger.

Code
HStack {    Text("Hello")    Text("World")        .background {            Color.green                .padding(
)
}}.padding(20)
Preview

We can also specify padding for specific edges only. For example, we can indent a view by setting padding on the leading edge:

Code
Color.blue    .padding(.leading, 
)
Preview

When we're proposing a nil dimension for a view, the padding amount is ignored when we propose to the padding's child. However, when the child reports its size, the padding value is added to the child's size.

Code
Text("Hello World")    .padding()    .background { Color.teal }    .fixedSize()
Preview
Tree

 

1/1