Bartłomiej Semańczyk
Bartłomiej Semańczyk

Reputation: 61860

How to background a whole cell of the List with SwiftUI?

This is how I define my List item:

var body: some View {
    NavigationView {
        List(groups) { group in
            NavigationLink {
                YearView(months: group.months)
            } label: {
                VStack(alignment: .leading, spacing: 3, content: {
                    Text(group.descriptiveYear)
                        .font(.system(size: 12))
                        .foregroundColor(.white)
                })
            }
            .background(Color.purple)
            .foregroundColor(.white)
        }
        .navigationTitle("Service")
    }
}

And this is the result:

enter image description here

But my intention was to background a whole cell with color and set text to white. How can I do it?

Upvotes: 0

Views: 75

Answers (2)

Elio_
Elio_

Reputation: 429

With listRowBackground added to your NavigationLink as follows

NavigationView {
      List(groups) { group in
           NavigationLink {
                YearView(months: group.months)
           } label: {
                VStack(alignment: .leading, spacing: 3, content: {
                    Text(group.descriptiveYear)
                        .font(.system(size: 12))
                        .foregroundColor(.white)
                })
           }
           .listRowBackground(Color.purple)
       }
       .navigationTitle("Service")
   }
}

Upvotes: 1

Kevin D
Kevin D

Reputation: 168

You can make use of the following modifier:

.listRowBackground()

https://developer.apple.com/documentation/swiftui/form/listrowbackground(_:)

Upvotes: 1

Related Questions