@brunowernimont

Change the background color in SwiftUI

January 29, 2021

SwiftUI background color ViewModifier Xcode

SwiftUI doesn’t have any view modifier to change the backround color from a view.
Instead, we need to create a ZStack with two views, the color fulfilling all the space and the view you want to have a background color.
So we’re going to create a ViewModifier to change the background color easily.

Creating a ViewModifier

struct BackgroundColorModifier: ViewModifier {
    let backgoundColor: Color
    
    func body(content: Content) -> some View {
        ZStack {
            backgoundColor.edgesIgnoringSafeArea(.all)
            content
        }
    }
}

extension View {
    func backgroundColor(_ color: Color) -> some View {
        modifier(BackgroundColorModifier(backgoundColor: color))
    }
}

Usage

Now wherever you want to change the background color, use: .backgroundColor(...).

struct ContentView: View {
    var body: some View {
        VStack {
            Text("How to change the background color")
            Text("Using a ViewModifier")
        }
        .backgroundColor(Color(.systemGroupedBackground))
    }
}