简体   繁体   中英

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 habe not able to. The view does no 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.

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

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
    }

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)
    }

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

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

尝试使用.background(Color.red)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM