How to create data tables with all columns displayed?

116 views Asked by At

I just recently started learning SwiftUI and found that my table had only 1 column and not the remaining columns from my JSON data. Can anyone please suggest how to display all the columns for a data table? Also, how can I search and sort a table? I've used jQuery DataTables and I don't know how to build these DataTables in SwiftUI.

Here's my code: DataProvider.swift

import Foundation
import SwiftUI

class DataProvider: ObservableObject {
    @Published var businesses:[Company] = []
    let url: URL
    
    func getBusinessList(){
        if let url = Bundle.main.url(forResource: "companies", withExtension: "json") {
               do {
                   let data = try Data(contentsOf: url)
                   let decoder = JSONDecoder()
                   let jsonData = try decoder.decode([Company].self, from: data)
                   self.businesses = jsonData
               } catch {
                   print("error:\(error)")
               }

           }
    }
    
    init(){
        self.url = URL(string: "http://localhost/output_json.php")!
        self.getBusinessList()
    }

}
struct Company: Codable, Hashable, Identifiable {
    var id: Int { s_no }
    var company, address, fax, phone, website: String
    var s_no: Int
}

ContentView.swift

import SwiftUI
import SwiftData

struct ContentView: View {
    @Environment(\.modelContext) private var modelContext
    @EnvironmentObject var provider: DataProvider
    
    var body: some View {
        Table( provider.businesses) {
            TableColumn("Name", value:\.company)
                TableColumn("Website", value:\.website)
            }
            }
    }


#Preview {
    ContentView()
        .modelContainer(for: Item.self, inMemory: true)
        .environmentObject(DataProvider())
}

ListViewerApp.swift

import SwiftUI
import SwiftData

@main
struct List_ViewerApp: App {
    var sharedModelContainer: ModelContainer = {
        let schema = Schema([
            Item.self,
        ])
        let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)

        do {
            return try ModelContainer(for: schema, configurations: [modelConfiguration])
        } catch {
            fatalError("Could not create ModelContainer: \(error)")
        }
    }()

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .modelContainer(sharedModelContainer)
        .environmentObject(DataProvider())
    }
}
0

There are 0 answers