I am a complete novice to Swift and I am writing a very simple application in SwiftUI for iOS 17 on Xcode 15.4. I would like to change the background colour of each row in a NavigationStack List to a colour name held in a string variable within a class. The data displayed in the list is pulled from an array of this class.
I have tried the following code which I expected to show a different colour on each row. The colour name is held in the MeritCard class in the name string.
import SwiftUI
import SwiftData
struct ContentView: View {
@Environment(.modelContext) var modelContext
@Query(sort: MeritCard.rank) var meritcards: [MeritCard]
var body: some View {
NavigationStack {
List {
ForEach(meritcards) {meritcard in
VStack (alignment: .leading) {
Text(meritcard.name)
.font(.headline)
}
.listRowBackground(Color(meritcard.name.lowercased()))
}
}
.navigationTitle("Your Meritcards")
.toolbar {
Button("Add Samples", action: addSamples)
}
}
}
I am using .listRowBackground(Color(meritcard.name.lowercased())) to attempt to alter the colour.
The code compiles fine but the background colour of each row remains white.
Jon Preston is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.