Search code examples
ioslistindexingswiftuibackground-color

SwiftUI List can't add index to alternate background colors


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

Solution

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