How can I reverse the list item in this looping, I wan to let the latest entry display on the top first.
List {
ForEach(self.entryController.moods, id: \.id)
{ mood in
HStack{
VStack {
Text(mood.monthString)
.font(.title2)
.fontWeight(.bold)
.foregroundColor(mood.emotion.moodColor)
Text("\(mood.dayAsInt)")
.font(.title2)
.fontWeight(.bold)
.foregroundColor(mood.emotion.moodColor)
}
RowView(mood: mood)
}
}.onDelete { (index) in
self.entryController.deleteMood(at: index)
}
}.refreshable {
await entryController.loadStats()}
I tried to use .reverse() function but It seems like can't work. Any solution on this?
CodePudding user response:
There are lots of pairs of functions in the standard library that have a mutating version and a non-mutating version - they are named like sort
and sorted
, and reverse
and reversed
. You need the non-mutating reversed method.
But really, this work should be in a view model, not in the view, so that moods, is maintained in the right order ready for the view
CodePudding user response:
The solution you are looking for is probably the following:
List {
ForEach(self.entryController.moods.reversed(), id: \.id)
{ mood in
HStack{
VStack {
Text(mood.monthString)
.font(.title2)
.fontWeight(.bold)
.foregroundColor(mood.emotion.moodColor)
Text("\(mood.dayAsInt)")
.font(.title2)
.fontWeight(.bold)
.foregroundColor(mood.emotion.moodColor)
}
RowView(mood: mood)
}
}.onDelete { (index) in
self.entryController.deleteMood(at: index)
}
}.refreshable {
await entryController.loadStats()
}
⚠️ Nevertheless I would handle the order of your data - as already mentioned by Shadowrun - in the view model