Reading time: 1 min

This recipe shows how to add a SwiftUI List with alternating row colors.

The end result looks like this:

preview_list

The tricks is to wrap an array of data in an indexed ForEach nested within a List and use the index to set different listRowBackground:

struct AlternatingRowsList<Data, Row: View>: View {
  let data: [Data]
  let firstColor: Color
  let secondColor: Color
  let viewMapping: (Data) -> Row

  init(_ data: [Data],
       firstColor: Color = .white,
       secondColor: Color = .gray.opacity(0.4),
       @ViewBuilder viewMapping: @escaping (Data) -> Row) {
    self.data = data
    self.firstColor = firstColor
    self.secondColor = secondColor
    self.viewMapping = viewMapping
  }

  var body: some View {
    let rowCount = data.count
    return List {
      ForEach(0..<rowCount) { index in
        viewMapping(data[index])
          .listRowBackground((index % 2 == 0) ? firstColor : secondColor)
      }
    }
  }
}

Then, you can use it like this:

var body: some View {
  AlternatingRowsList(Array(1...50)) { item in
    Text("\(item)")
  }
}

Next Post Previous Post