Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI List with alternate background colors

In SwiftUI, TableView 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.

like image 300
Dids Avatar asked Sep 13 '19 07:09

Dids


People also ask

How do I change the background of a list in SwiftUI?

We can change the background color of a list row in SwiftUI with listRowBackground(_:) modifier. To set a list row background color, add listRowBackground(_:) modifier to the list row item.

How do I customize a list in SwiftUI?

To begin, create a SwiftUI Xcode project, and create a struct , namely, Data . Let's get back in our ContentView. swift and populate some values into this struct . Now, inside your view, create a List, and use ForEach to add and see all your data in list form.

How do I specify colors in SwiftUI?

Search for the assets folder in your project, once inside you'll see everything that's added to the folder such as images, your app icon, etc. You need to create a new color by right-clicking anywhere in the list to open a menu, just click Color Set and you name the color however you want.


1 Answers

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))
    }
}
like image 175
KB-YYZ Avatar answered Sep 20 '22 21:09

KB-YYZ