How to Set the Background Color in SwiftUI

SwiftUI-BackgroundColors.png

It took me longer than I’d care to admit to figure out how to set the background color for a full screen view in SwiftUI. Read on to avoid my mistakes and learn how to quickly and easily set the background color for your views!

Since all of SwiftUI is built with the concept of combining Views together to create more complex Views, it totally makes sense that setting a background color would work the same way. But instead of having to create a custom, empty View with the color you want you can actually just use Color directly since it is a View itself!

var body: some View {
    Color.blue
}

That’s all you really need to add a background color! But wait, something looks a little off…

WithSafeArea.png

What’s all that extra space on the top and bottom? That’s the safe area insets. The layout engine automatically tries to lay things out within its determined “safe area” to prevent problems with your UI such as the notch covering up something important. It’s super easy to tell the layout engine to ignore the safe area by adding one modifier to our Color:

var body: some View {
    Color.blue
        .edgesIgnoringSafeArea(.all)
}
IgnoreSafeArea.png

And there you go, full screen background color! Now just throw that Color into a ZStack as the first item and you can build everything else out on top of it.

Check out some more recent tutorials

Previous
Previous

Splitting Strings in Swift

Next
Next

How to Update Text Using a TextField in SwiftUI