magnuskahr

writing code

SwiftUI: List row background

Dear future me. Have you remembered how to handle backgrounds in a list yet? Perhaps Apple changed things up, and it doesn’t suck anymore? But, if not - let me help you.

The Problem

The modifier .listRowBackground sounds like it should do the job, and looking at the documentation it clearly should:

listRowBackground(_:)
Places a custom background view behind a list row item.

Moreover, from the documentation we are also clearly given some code:

struct ListRowBackground: View {

    enum Flavor: String, CaseIterable, Identifiable {
        var id: String { self.rawValue }
        case vanilla, chocolate, strawberry
    }

    var body: some View {
        List(Flavor.allCases, id: \.self) {
            Text($0.rawValue)
        }
        .listRowBackground(Image(systemName: "sparkles"))
    }
}

However. this. does. not. work.

Also, it does not work when applying the modifier on the list item it self.

The solution

It turns out that the modifier only works when applied in a ForEach, so the following will work:

List {
    ForEach(Flavor.allCases, id: \.self) {
        Text("Row \($0.rawValue)")
    }
    .listRowBackground(Color.red)
}

Which will apply the same background to all items of a list, but we can also do in for a single item:

var body: some View {
    List {
        ForEach(Flavor.allCases, id: \.self) {
            if $0 == .strawberry {  
                Text("Row \($0.rawValue)")
                .listRowBackground(Color.red)
            } else {
                Text("Row \($0.rawValue)")
            }
        }
    }
}