Home > Enterprise >  SwuiftUI Custom Sorting
SwuiftUI Custom Sorting

Time:02-14

I'm just starting out in SwuiftUI so bear with me. I have a Game stuct that has a field lastUpdated and title. I want to have the choice to sort by my list by lastUpdated or title. But I'm not sure how this works. I've looked into sorted(by:) but I can't really get anything to work. Suggestions?

struct Game: Identifiable, Codable {
let id: UUID
var title: String
var players: [Player]
var lastUsed: Date }

GameView

struct GameListView: View {
@Binding var games: [Game]
    
var body: some View {
    
    List {
        ForEach($games) { $game in
            NavigationLink(destination: GameView(game: $game)) {
                Text(game.title)}
            }
        }

CodePudding user response:

The scenario is slightly complicated by the Binding form of ForEach, but you should still be able to return a sorted collection. It might look like this:

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)}
            }
        }
    }
}
  • Related