Search code examples
listswiftuirowbackground-colorswiftui-list

Modify Row Background Colour List SwiftUI


I'm trying to change the row colour in the list.

struct ContentView: View {
@State var userProfiles : [Profile] = [Profile.default]

var body: some View {
    VStack{
    List(userProfiles.indices, id: \.self, rowContent: row(for:)).background(Color.red)
    }.background(Color.red)
}

// helper function to have possibility to generate & inject proxy binding
private func row(for idx: Int) -> some View {
    let isOn = Binding(
        get: {
            // safe getter with bounds validation
            idx < self.userProfiles.count ? self.userProfiles[idx] : DtrProfile.default
        },
        set: { self.userProfiles[idx] = $0 }
    )
    return Toggle(isOn: isOn.isFollower, label: { Text("\(idx)").background(Color.red) } )
   }
}

Output:-

Screenshot

I want to achieve:-

Screenshot

Can someone please explain to me how to change the full row colour. I've tried to implement by above but no results yet.

Any help would be greatly appreciated.

Thanks in advance.


Solution

  • Use listRowBackground

    var body: some View {
        VStack{
            List {
                ForEach(0...15, id: \.self, content: row(for:)).background(Color.red).listRowBackground(Color.red)
            }
        }
    }