SwiftUI List with alternate background colors
Asked Answered
S

2

10

In SwiftUI, UITableView is replaced with List.

Is there a way to alternate the background colors of the list's cells/rows?

I would like to implement something like this:

if (indexPath.row % 2 == 0) { 
    aCell.backgroundColor = UIColor(red: 0, green: 1, blue: 0, alpha: 1.0) 
}

See article https://medium.com/@ronm333/improving-the-appearance-of-ios-tableviews-9effb7184efb for a good example.

Sorensen answered 13/9, 2019 at 7:24 Comment(0)
B
11

I use something along these lines to alternate list background colours in my SwiftUI lists

List {
    ForEach(items.indices) { index in
        Text(items[index])
            .listRowBackground((index  % 2 == 0) ? Color(.systemBlue) : Color(.white))
    }
}
Boehmenism answered 13/9, 2019 at 14:2 Comment(3)
Seems like this solution has an Apple bug if you have a segmented control: "count (7) != its initial count (10). ForEach(_:content:) should only be used for constant data."Langford
Interestingly, this only works if I include the ForEach { … }Mccutcheon
this gives the "Non-constant range: not an integer range" warning and works only with indices not with an enumerated array but adding id to loop like here ForEach(items.indices, id: \.self) would fix the problemPetcock
C
21

SwiftUI now supports this on macOS Monterey through inset(alternatesRowBackgrounds:).

.listStyle(.inset(alternatesRowBackgrounds: true))

Cadena answered 8/6, 2021 at 15:18 Comment(0)
B
11

I use something along these lines to alternate list background colours in my SwiftUI lists

List {
    ForEach(items.indices) { index in
        Text(items[index])
            .listRowBackground((index  % 2 == 0) ? Color(.systemBlue) : Color(.white))
    }
}
Boehmenism answered 13/9, 2019 at 14:2 Comment(3)
Seems like this solution has an Apple bug if you have a segmented control: "count (7) != its initial count (10). ForEach(_:content:) should only be used for constant data."Langford
Interestingly, this only works if I include the ForEach { … }Mccutcheon
this gives the "Non-constant range: not an integer range" warning and works only with indices not with an enumerated array but adding id to loop like here ForEach(items.indices, id: \.self) would fix the problemPetcock

© 2022 - 2024 — McMap. All rights reserved.