I have two Views (main and filter). For my filter view, there are Pickers that the user can choose from that will filter data that is hardcoded inside an array. In the main view, the array is being called within a for each loop that will display the data on a LazyVGrid view. However, for some reason, the view is not updating when I filter the data.
The Filter view
import SwiftUI
struct Filter: View {
@Binding var sortIndex: Int
@ObservedObject var model: MarketDataViewModel
var sort = ["Lowest to Highest", "Highest to Lowest"]
var body: some View {
Form {
Section(header: Text("Filtering")){
Picker(selection: $sortIndex, label: Text("Sort by")) {
ForEach(0..<sort.count) {
Text(self.sort[$0])
}
}.onChange(of: sortIndex, perform: { value in
model.data.sort(by: {$0.price < $1.price})
print(model.data)
print("__________________________________")
})
} .navigationBarTitle("Filters")
}
}
The Main view
import SwiftUI
struct MarketPlace: View {
@State var sortIndex = 0
@StateObject var item = MarketDataViewModel()
var body: some View {
NavigationView {
VStack {
HStack{
NavigationLink(destination: Filter(sortIndex: $sortIndex, model: MarketDataViewModel())) {
Image("Filter")
.resizable()
}
Spacer()
.frame(width: 15)
}
}
CodePudding user response:
here, NavigationLink(destination: Filter(sortIndex: $sortIndex, model: MarketDataViewModel()))
you create a new MarketDataViewModel every time you click on it. You should have: NavigationLink(destination: Filter(sortIndex: $sortIndex, model: item)). That way you use the single source of truth, your @StateObject var item = MarketDataViewModel().
