Home > Software engineering >  How to make a List background black in SwiftUI?
How to make a List background black in SwiftUI?

Time:04-10

What I did to make the entire screen black is to use this construction in my view:

    ZStack {
       Color.black.ignoresSafeArea()  }

And for the List modifiers I used the following two:

    .listRowBackground(Color.black) 
    .listStyle(.plain)

This works great.

But then I want to add a view on top of my List (like a header) and some white space appears around it ? Where does that come from ? And how can I change it to black ?

enter image description here

Here is my complete code:

struct WorkoutView: View {
    var body: some View {
        ZStack {
        Color.black.ignoresSafeArea()
        List {
            TempView()
            
            ForEach(1..<30) { index in
                VStack(alignment: .leading, spacing: 4) {
                    Text("one line")
                        .foregroundColor(.white)
                        .font(.title)
                        .fontWeight(.bold)
                }
                .padding(.vertical)
            }
            .listRowBackground(Color.black)
        }
        .listStyle(.plain)
        }
    }
}

struct TempView: View {
    var body: some View {
        ZStack(alignment: .leading) {
            Color.black.ignoresSafeArea()
            
            Text("Hello World")
                .foregroundColor(.red)
                .font(.largeTitle)
                .bold()
        }
    }
}

CodePudding user response:

Just do the same thing you did for the ForEach: add a .listBackground() modifier. Like this:

TempView()
    .listRowBackground(Color.black)

enter image description here

  • Related