SwiftUI Filtered Table
A Table in SwiftUI is used to present data in rows and columns.
To create a table insert a `Table` view and nested in there `TableColumn`s. Table data can be filtered and the table will update automatically. However, the filter process itself must be implemented by the developer.
import SwiftUI
struct SampleFilteredTableView: View {
class Record: ObservableObject, Identifiable {
var id: UUID = UUID()
@Published var firstName: String
@Published var lastName: String
@Published var age: Int
@Published var city: String
init(firstName: String, lastName: String, age: Int, city: String) {
self.firstName = firstName
self.lastName = lastName
self.age = age
self.city = city
}
}
@State private var records: [Record] = []
@State private var viewableRecords: [Record] = []
@State private var cities: [String] = ["All Cities"]
@State private var selectedCityIndex: Int = 0
var body: some View {
VStack(alignment: .leading) {
HStack {
Text("Table")
}
.font(.title)
HStack {
Spacer()
Picker("City", selection: $selectedCityIndex, content: {
ForEach(Array(0 ..< cities.count), id: \.self) { index in
Text(cities[index]).tag(index)
}
}, currentValueLabel: {
Text(cities[selectedCityIndex])
})
.frame(width: 200)
}
Table(viewableRecords, columns: {
TableColumn("First Name", value: \.firstName)
TableColumn("Last Name", value: \.lastName)
TableColumn("Age", content: { rec in
Text("\(rec.age)")
})
.alignment(.center)
TableColumn("City", value: \.city)
})
}
.task() {
loadData()
}
.onChange(of: selectedCityIndex, {
filterRecords()
})
}
private func filterRecords() {
viewableRecords = selectedCityIndex == 0 ?
records :
records.filter({
$0.city == cities[selectedCityIndex]
})
}
private func loadData() {
records = [
Record(firstName: "John", lastName: "Smith", age: 50 , city: "Vancouver"),
Record(firstName: "Jim", lastName: "Johnson", age: 20 , city: "Vancouver"),
Record(firstName: "Jane", lastName: "Doe", age: 30 , city: "Toronto"),
Record(firstName: "John", lastName: "Doe", age: 32 , city: "Toronto"),
Record(firstName: "Alice", lastName: "Anderson", age: 25 , city: "Montreal"),
Record(firstName: "Bob", lastName: "Brown", age: 40 , city: "Calgary"),
Record(firstName: "Jim", lastName: "Doe", age: 35 , city: "Toronto"),
]
cities = ["All Cities"] + Set(records.map({ $0.city })).sorted()
selectedCityIndex = 0
filterRecords()
}
}
#Preview {
SampleFilteredTableView()
}