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.
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.
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.
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.
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))
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With