Set Background Color for Entire Screen in SwiftUI


In this tutorial, you are going to learn various ways to set the screen background color for the entire screen in SwiftUI with examples. Below are given 3 easy examples to set background color for the entire screen using different types of views:

Using background modifier for VStack

We can set the VStack view for the entire screen using the frame() method and then use the background modifier to set the background color of our entire screen. Below is given the SwiftUI code where we are applying the background color green to our VStack view:

import SwiftUI

struct ContentView: View {
    
    var body: some View {
        
        VStack {
            
            Text("Welcome to our app")
            
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.green) // Set green background color
        
    }
}

The frame() method in the above Swift program helps us to occupy the background for the whole space.

Using Overlay Modifier

Below is another example where we are using the overlay() modifier of SwiftUI to set the background color mint for our app:

import SwiftUI

struct ContentView: View {
    
    var body: some View {

        // Set the background color mint
        Color.mint
            .ignoresSafeArea()
            .overlay(
                VStack(spacing: 30) {
                    Text("Look at background").font(.largeTitle)
                    Text("Welcome to SwiftSpeedy").font(.title)
            })
        
    }
}

In the above code, we have used the ignoresSafeArea() method to prevent our main content from ignoring the safe edges area also.

Using ZStack

Now it’s time to do it for the ZStack view. ZStack is useful when you want to align one view to another.

Below is how we can set the background color to indigo in ZStack:

import SwiftUI

struct ContentView: View {
    
    var body: some View {

        
        ZStack {
            // Set background color to indigo
            Color.indigo
            VStack {
                
                Text("This is our app content")
                
            }
        }
        
    }
}

I hope you will now be able to set the background color of your app after reading this tutorial.