Skip to main content

How to color the padding around a view

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to color the padding around a view 관련

SwiftUI by Example

Back to Home

How to color the padding around a view | SwiftUI by Example

How to color the padding around a view

Updated for Xcode 15

The padding() modifier lets us add some spacing around a view, and the background() modifier lets us set a background color. However, the way you use them matters, so it’s important to be clear about your goal in order to get the best results.

As an example, this creates a text view with a red background and white foreground, then adds system default padding to it:

Text("Hacking with Swift")
    .background(.red)
    .foregroundStyle(.white)
    .padding()

Download this as an Xcode projectopen in new window

The text “Hacking with Swift” on a red background. There is little space between the text's edges and the rectangle's edges.
The text “Hacking with Swift” on a red background. There is little space between the text's edges and the rectangle's edges.

And this adds system default padding then sets a red background color and a white foreground:

Text("Hacking with Swift")
    .padding()
    .background(.red)
    .foregroundStyle(.white)

Download this as an Xcode projectopen in new window

The text “Hacking with Swift” on a red background. There is some red space around the text between its edges and the rectangle's.
The text “Hacking with Swift” on a red background. There is some red space around the text between its edges and the rectangle's.

Those two pieces of code might look similar, but they yield different results because the order in which you apply modifiers matters. In the second example the view is padded then colored, which means the padding also gets colored red. In contrast, the first example colors then pads, so the padding remains uncolored.

So, if you want some text to have a background color wider than the text itself, make sure to use the second code example – pad then color.

Similar solutions…
How to control spacing around individual views using padding | SwiftUI by Example

How to control spacing around individual views using padding
How to add extra padding to the safe area | SwiftUI by Example

How to add extra padding to the safe area
How to draw a border around a view | SwiftUI by Example

How to draw a border around a view
How to draw a shadow around a view | SwiftUI by Example

How to draw a shadow around a view
SwiftUI tips and tricks | SwiftUI by Example

SwiftUI tips and tricks

이찬희 (MarkiiimarK)
Never Stop Learning.