'How to set a background color for the viewController in swiftUI?

I have been trying to set a background color for the whole viewController in swiftUI but I have not able to. The view does not take the attribute .backgroundColor .

I have tried using the .backgroundColor attribute for the viewController in sceneDelegate too and it is not taking the attribute but it takes the foregroundColor attribute.



Solution 1:[1]

So far, what I have found to work best is to create a ZStack at the top of the ContentView body and have the first layer a Color, that ignores the safe area. Apple defines a Color as "a late-binding token", whatever that is, but it behaves similar to any other View.

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

      /// Your Inner View content goes here.
      VStack {
        Text("Hello") 
      } // VStack

    } // ZStack
  } // body View
}  // ContentView

Note: Be careful about what is inside the Inner View because it can easily expand to fill the entire window thus overlaying your background color with white, etc. For example, the popular NavigationView tends to expand to the entire window and for me it tends to ignore its documented .background() setting. You can do the same ZStack strategy here too.

NavigationView {
  ZStack { 
    Color.red.edgesIgnoringSafeArea(.all) 
    VStack {
      Text("Hello")
    } // VStack
  } // ZStack
}  // NavigationView

Solution 2:[2]

If you use the background modifier (.background(Color.red)) on the top view, you just will be wrapping that view with a new view with background color red around his padding or size. So you should use a Rectangle() view and a Z stack to set a full background to the whole view, and if you need, use the .edgesIgnoringSafeArea

    NavigationView {
        ZStack { 
            Rectangle().foregroundColor(.blue).edgesIgnoringSafeArea(.all)
            ScrollView {
                List()
                    ForEach(modelExampleList) { modelExample in
                        Row(model: modelExample)
                    }
                }.frame(height: 200)
            }.padding(.leading, 10)
        }.navigationBarTitle(Text("ModelExample List"), displayMode: .large)
    }

Solution 3:[3]

you can use below code for change whole of view controller color

ZStack {
        Color.red
        .edgesIgnoringSafeArea(.all)
    }

and use this code for change safe area background color

ZStack {
        Color.red
    }

Solution 4:[4]

I moved it out of the ZStack, then used an overlay and it worked.

var body: some View {
    NavigationView {
        sceneBackgroundColor
            .edgesIgnoringSafeArea(.all)
            .overlay(myView)
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Piero Sifuentes
Solution 3 Masoud Roosta
Solution 4 Alex