Reputation: 303
How can I keep my filter selections when view dismiss . Im trying to make a filter pop up view but I couldn't figure out how to keep my selections when user press filter button. Selections array where I put my filter selections. When user press filter button my popup view will dismiss and I want to display user selections when filter view open again.
struct FilterPopUpView: View {
@State var filterListArray : [ProductListSortAndFilterList]
@Binding var popUpOpened : Bool
@State var selections : [String] = []
@State var isApply : Bool = false
@State var isMarked : Bool = false
@State var filterApply : Bool = false
@Environment (\.presentationMode) var Presentation
var body: some View {
NavigationView {
ZStack{
List {
ForEach(filterListArray.filter{ $0.id != "sort" && $0.id != "stock"}, id:\.id) { data in
NavigationLink(destination : FilterDetailView(filterDetailList: data.sortAndFilterList ?? [], navigationBarTitle: data.name ?? "", selectionFilters: $selections, isApply: $isApply, selectSingle: data.selectSingle ?? 1)
){
VStack(alignment: .leading,spacing:10){
FilterCell(filterType: data)
HStack{
ForEach(selections, id:\.self ) { item in
if isApply == true {
SelectedFiltersRow(filterSelection: item, sortAndFilterData: data)
}
}
}
}
}
}
ForEach(filterListArray , id:\.id) { item in
if item.name == "Stoktakiler" {
HStack {
FilterCell(filterType: item)
Spacer()
CheckBoxField(isMarked: $isMarked)
}.contentShape(Rectangle())
.onTapGesture {
isMarked.toggle()
}
}
}
}
.navigationBarTitle(Text("Filtrele"),displayMode: .inline)
.buttonStyle(PlainButtonStyle())
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button("Temizle")
{
self.selections.removeAll()
isMarked = false
}
}
ToolbarItem(placement: .navigationBarLeading) {
Button("Cancel")
{
print("Cancel tapped!")
popUpOpened = false
}
}
}
Button(action: {
filterApply == true
self.Presentation.wrappedValue.dismiss()
}) {
FilterButton()
}.offset(x: 0, y: UIScreen.main.bounds.height * (0.4))
}.onAppear {
print(selections)
}
}
}
}
Upvotes: 0
Views: 296
Reputation: 52555
You'll need to store the state at least one level up in your view hierarchy and then pass it to FilterPopUpView
as a parameter.
I'd probably encapsulate all of the filter state in one struct like:
struct FilterState {
var selections : [String] = []
var isApply : Bool = false
isMarked : Bool = false
var filterApply : Bool = false
}
Then, store that as a @State on your parent view:
@State private var filterState = FilterState()
And on your FilterPopUpView
:
@Binding var filterState : FilterState
And then pass it as a parameter when you open the popup. That way, it'll retain state between openings.
Upvotes: 1