我剛開始使用 SwuiftUI,所以請耐心等待。我有一個包含 lastUpdated 和 title 欄位的 Game stuct。我希望可以選擇按 lastUpdated 或標題按我的串列排序。但我不確定這是如何作業的。我已經研究過 sorted(by:) 但我真的什么都做不了。建議?
struct Game: Identifiable, Codable {
let id: UUID
var title: String
var players: [Player]
var lastUsed: Date }
游戲視圖
struct GameListView: View {
@Binding var games: [Game]
var body: some View {
List {
ForEach($games) { $game in
NavigationLink(destination: GameView(game: $game)) {
Text(game.title)}
}
}
uj5u.com熱心網友回復:
該場景因 的Binding形式而略微復雜ForEach,但您仍然應該能夠回傳已排序的集合。它可能看起來像這樣:
struct GameListView: View {
@Binding var games: [Game]
@State var sortType : SortType = .lastUsed
enum SortType {
case lastUsed, title
}
var sortedGames : [Binding<Game>] {
$games.sorted(by: { a, b in
switch sortType {
case .lastUsed:
return a.wrappedValue.lastUsed < b.wrappedValue.lastUsed
case .title:
return a.wrappedValue.title < b.wrappedValue.title
}
})
}
var body: some View {
List {
ForEach(sortedGames) { $game in
NavigationLink(destination: GameView(game: $game)) {
Text(game.title)}
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/427523.html
上一篇:按唯一名稱和最新日期排序
