Home > Enterprise >  SwiftUI List can't add index to alternate background colors
SwiftUI List can't add index to alternate background colors

Time:10-06

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))
    }
}

CodePudding user response:

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

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

CodePudding user response:

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)
}
  • Related