Filtered list when going back from pushed view

I have the below code for my view's body

Currently when I go to the ItemDetailView View and then press back to return to this view, the filtered list is no longer there, it's back the full view. How to I get it to keep the filtered list when I go back? The text is still in the search bar

        NavigationLink(destination: ItemAddView(series: series), isActive: $noItemsShowing) { EmptyView() }
        List {
            ForEach(items) { item in
                NavigationLink(destination: ItemDetailView(item: item)) {
                    Text(fullItemName(item: item))
                }
            }
        }
        .searchable(text: $searchText)
        .onSubmit(of: .search) {
            items.nsPredicate = NSPredicate(format: "series = %@", series)
            if(!searchText.isEmpty) {
                items.nsPredicate = NSPredicate(format: "series = %@ AND amount > 0 AND name CONTAINS[cd] %@", series, searchText)
            }
        }
        .onChange(of: searchText) { _ in
            items.nsPredicate = NSPredicate(format: "series = %@", series)
            if(!searchText.isEmpty) {
                items.nsPredicate = NSPredicate(format: "series = %@ AND amount > 0 AND name CONTAINS[cd] %@", series, searchText)
            }
        }
        .navigationBarTitle("\(series.name ?? "Error") Items", displayMode: .inline)
    }

Accepted Reply

Seems like I can alter the onAppear method to do what I want

        .onAppear() {
            items.nsPredicate = NSPredicate(format: "series = %@ AND amount = 0", series)
            if(!searchText.isEmpty) {
                items.nsPredicate = NSPredicate(format: "series = %@ AND amount = 0 AND name CONTAINS[cd] %@", series, searchText)
            }
        }

Replies

As we do not see the full code (how is items built ?), I am not sure of my suggestion.

Could you create a State var to hold the filtered list (which would be the full list if not filtered) and use it in ForEach ?

  • Items comes from a French request from core data

Add a Comment

Seems like I can alter the onAppear method to do what I want

        .onAppear() {
            items.nsPredicate = NSPredicate(format: "series = %@ AND amount = 0", series)
            if(!searchText.isEmpty) {
                items.nsPredicate = NSPredicate(format: "series = %@ AND amount = 0 AND name CONTAINS[cd] %@", series, searchText)
            }
        }