
在SwiftUI中,如果想要在List和ForEach显示的列表进行字段排序,可以使用sorted(by:) 方法。
例如,原先的List为:
List {
ForEach(piggyBank.records, id: \.self) {record in
Section {
...
}
}
}
如果想要对某一个字段进行排序,可以在ForEach中添加sorted方法。
ForEach(piggyBank.records.sorted( by: { $0.date > $1.date }), id: \.self) { record in
...
}

最终就可以在视图中查看到按照视频排序的记录。
如果还想要显示显示的信息条数,还可以使用prefix(_:) 方法限制显示的数量。
List {
ForEach(piggyBank.records.sorted(by: { $0.date > $1.date }).prefix(3), id: \.self) {record in
Section {
...
}
}
}
