TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Working with SwiftUI Table and SwiftData

Forums > SwiftUI

Hello, i am at beginning of my iOS dev journey and while writting my app the problem with fetching data from SwiftData to Table view occured. When using data simply from @Query macro it is not possible to sort data in the Table as you can do with simple Array of objects or i just didn't find a good solution. I did a workaround, which i found on stack and it works so that i copy data from query to new array and sort it as usual. But it is getting dirty when i want to edit item or delete it. I don't know how should i do it properly and didn't find good solution yet.

Here is the model:

@Model
final class BuildingModel: Identifiable {
    var id: UUID
    var buildingName: String
    var buildingFloors: Int

    init(id: UUID = UUID(), buildingName: String = "", buildingFloors: Int = 0) {
        self.id = id
        self.buildingName = buildingName
        self.buildingFloors = buildingFloors
    }
}

and the view:

struct BuildingView: View {
    @Environment(\.modelContext) var context
    @Query private var buildings: [BuildingModel]
    @State private var selectedBuilding = Set<BuildingModel.ID>()
    @State private var sortOrder = [KeyPathComparator(\BuildingModel.buildingName)]

    var sortedBuildings: [BuildingModel] {
        buildings.sorted(using: sortOrder)
    }

    @State private var isPresentOn = false

    var body: some View {
        NavigationStack{
            VStack{
                Table(sortedBuildings, selection: $selectedBuilding ,sortOrder: $sortOrder) {
                    TableColumn("Name", value: \.buildingName)
                    TableColumn("Floors", value: \.buildingFloors){
                        value in
                        Text("\(value.buildingFloors)")
                    }
                }
                .onChange(of: sortOrder) {
                    sortedBuildings.sorted(using: $0)
                }
            }
            .navigationTitle("Buildings")
                .sheet(isPresented: $isPresentOn) {
                    ///View for adding new item that works fine

                }
                .toolbar {
                    ToolbarItem(placement: .primaryAction) {
                        HStack{
                            Button {
                                isPresentOn.toggle()
                            } label: {
                                Label("+", systemImage: "plus")
                            }
                            Button {
                                //Lack here
                            } label: {
                                Label("Delete", systemImage: "trash")
                            }
                            Button {
                                //Lack here
                            } label: {
                                Label("Edit", systemImage: "building")
                            }
                        }

                    }

                }
        }
    }
}

As i said i am begginer, so i would be grateful for any tips how to do or change it, or existing materials which i did not found.

2      

@david is a bit lost on his SwiftUI journey...

Hello, i am at beginning of my iOS dev journey and while writting my app
the problem with fetching data from SwiftData to Table view occured.

There are several excellent tutorial on this web site, some specifically geared to answer SwiftData questions and even your question about combining @Query with SortDescriptors!

Take a few days and give your project a rest. Instead, cozy up to HackingWithSwift and learn from one of the best Swift instructors around. For starters, work through the entire Bookworm project.

Actually, I'd recommend you go throught the entire 100 Days of SwiftUI course. Some of the language in your message above indicates you may not (exactly) understand SwiftUI, and SwiftData terms and concepts. If you do, then the review would be a great refresher for you.

TBH, I think you came here looking for an answer and maybe you didn't even look to see what resources were available to help you learn SwiftData? We're supposed to be supportive and to criticize ideas, not the people expressing them. With this in mind, I encourage you to review the materials in this excellent site.

See -> Bookworm Project

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.