Background Color with SwiftUI

Kristaps Grinbergs
Level Up Coding
Published in
4 min readDec 29, 2020

--

Once you create a SwiftUI view, it has the default background color, white for light mode and black for dark mode respectively. How can you change it to something different? Let’s look into that today.

Photo by AB on Unsplash.

In this article, we will talk about different techniques that we can use to change the default background for our SwiftUI views.

Using modifier

The first approach that comes to mind is using .background() modifier. Sadly Apple hasn't provided documentation for this. It takes in a view that is set as a background for the view we are adding this modifier to.

In this case, we want to change the background color. For instance, we can pass in Color.gray.

Text("Hello, world!")
.background(Color.gray)

We see that it sets the background color only for the text view. That is how SwiftUI works. We want to set it for the whole screen. We could approach it using VStack, HStack, and a couple of Spacer() views.

VStack {
Spacer()
HStack {
Spacer()
Text("Test")
Spacer()
}
Spacer()
}.background(Color.gray)

It looks a bit better, but we want to set it for the whole screen, ignoring the safe area. We can do it using .edgesIgnoringSafeArea modifier. Using this modifier, we can tell the SwiftUI layout engine to extend outside the screen's safe area. It takes in a parameter that defines which edges we can expand. In this case, we will pass in .all.

.background(Color.gray.edgesIgnoringSafeArea(.all))

It looks exactly how we wanted. The issue is that the code is quite cumbersome and has a lot of nesting views and spacers. Let’s look at it in another way. ​

Using ZStack

--

--

Blockchain, mobile and fullstack developer. Startup founder. Conference speaker. Mentor. Passionate about building products, sustainability and Web 3.0.