SwiftUI - How do I change the background color of a View?

jeremyabannister picture jeremyabannister · Jun 4, 2019 · Viewed 90.6k times · Source

I'm beginning to try out SwiftUI and I'm surprised that it doesn't seem to be straightforward to change the background color of a View. How do you do this using SwiftUI?

Answer

Simon picture Simon · Jun 4, 2019

You can do something like:

.background(Color.black)

around your view.

eg. from the default template (I am encompassing it around a Group):

    var body: some View {
        VStack {
          Text("Hello SwiftUI!")
        }
       .background(Color.black)
    }

To add some opacity to it, you can add the .opacity method as well:

.background(Color.black.opacity(0.5))

You can also make use of the inspect element of the view by CMD + click on the View and clicking Show SwiftUI Inspector > Background > Your Color

Inspect View

Inspect Detail View