Home > Blockchain >  How to alternate background color of records in ScrollView | SwiftUI
How to alternate background color of records in ScrollView | SwiftUI

Time:08-05

Essentially I would like to alternate the background colors of rows in ScrollView, following the pattern white, gray, white, gray, etc.

How can this be done?

@State var posts: [Item] = []
@State var expanded = false
@State var totalRows = 0

ForEach(posts.prefix(expanded ? totalRows : 5), id: \.id) { post in
    Label {
        VStack(alignment: .leading) {
            Text(convertDate(post.date))
        }
        .padding(.leading, 8)
    }  icon: {}
}

.frame(width: UIScreen.main.bounds.width - 35, height: 85, alignment: .leading)
.background(Color("cellColor")) //<-- Currently Setting Color Here
.cornerRadius(10)

Struct Codable for JSON

struct Item: Codable, Hashable, Identifiable {
    var id = UUID()
    var date: String
    var name: String
    var occupation: String
}

CodePudding user response:

Try something like this:

 List { // <-- here
    ForEach(Array(posts.prefix(expanded ? totalRows : 5).enumerated()), id: \.0) { index, post in  // <-- here
         VStack {
             Label {
                 VStack(alignment: .leading) {
                     Text(convertDate(post.date))
                 }
                 .padding(.leading, 8)
             } icon: {}
         }
         .listRowBackground(index % 2 == 0 ?  Color.gray : Color.white) // <-- here
     }
 }
 .frame(width: 333, height: 444, alignment: .leading) // <-- for testing
 .cornerRadius(10)

If you want to use a ScrollView instead of a List, use .background(index % 2 == 0 ? Color.gray : Color.white) instead of the .listRowBackground(...)

Note, with minor adjustments you can also use .indices instead of .enumerated().

  • Related