1

How to implement alternate list background colors in my SwiftUI lists to display system colors or custom colors.

import SwiftUI

struct FriendshipListView: View {
    
    @EnvironmentObject var listViewModel: MenuListFriendshipViewModel
    
    var body: some View {
        NavigationView {
            List {
                //Use the $ syntax to pass a binding on to the subviews
                ForEach($listViewModel.items) { $item in
                    MenuListRowView(item: $item)
                }
            }
            .navigationBarTitle(Text("Friendships / Relationships"))
            .listStyle(PlainListStyle())
        }
    }
}

struct ListView_Previews: PreviewProvider {
    static var previews: some View {
        FriendshipListView()
        .environmentObject(MenuListFriendshipViewModel())
    }
}

I was trying to implement this code snippet but just don't understand how to apply [index] to my ForEach loop.

List {
    ForEach(items.indices) { index in
        Text(items[index])
            .listRowBackground((index  % 2 == 0) ? Color(.systemBlue) : Color(.white))
    }
}
1

2 Answers 2

1

in your particular case, with the binding required, try this approach, works for me:

ForEach($listViewModel.items) { $item in
    let index = listViewModel.items.firstIndex(where: {$0.id == item.id})
    MenuListRowView(item: $item)
        .listRowBackground(((index ?? 0) % 2 == 0) ? Color.blue : Color.red)
}
Sign up to request clarification or add additional context in comments.

Comments

1

It's the same way as the code snippet. Set listRowBackground under the MenuListRowView(item: $item)

MenuListRowView(item: $item)
    .listRowBackground(Color.green)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.