Search code examples
iosswiftlistswiftuibackground-color

SwiftUI List with alternate background colors


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.


Solution

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