SwiftUI Background Color Tutorial

In SwiftUI the background color can be applied to every view. To change the background color to the whole screen a ZStack must be used. In this tutorial a red background color is set using a ZStack . SwiftUI requires Xcode 11 and MacOS Catalina, for which the Betas can be downloaded at the Apple developer portal.

Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select the Single View App template, and then click Next. Enter SwiftUIBackgroundColorTutorial as the Product Name, select the Use SwiftUI checkbox, and click Next. Choose a location to save the project on your Mac.

In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.

In the Project navigator, click to select ContentView.swift. Change the code inside the ContentView struct to

struct ContentView: View {
    var body: some View {
        ZStack {
            Color.red
        }
    }
}

ZStack is a stack type for creating overlapping content. The red color is set inside the ZStack

The preview will look like this.

The background color is applied to the safe area. To change the color background outside the safe area the .edgesIgnoringSafeArea() modifier must be used.

struct ContentView: View {
    var body: some View {
        ZStack {
            Color.red
            .edgesIgnoringSafeArea(.all)
        }
    }
}

Now the preview updates the background color outside the safe area.

The source code of the SwiftUIBackgroundColorTutorial can be downloaded at the ioscreator repository on Github.