Hello guys!
I have a view with a viewModel and I have a save function in the viewModel that I linked to the view .onDisppear
Modifier. When I have this setup, if I have a navigation link or a picker whos style is a navagiation link, the navigation link immediatly pop pack to it's parent view. After a lot of searching, I found that the cause of that is that the .OnDisappear
is called when we navigate further, so the data changes and the view redraw itself. In the case of the NavigationLink
I could hack around it and set its isActive
to a property in the model and set it back to false when the inner view disAppear, so then when I call the save function I check that all the active properties are false then save, but in Picker
we don't have the option of settings if it's active or not. What would you guys recomend to do to go around that?
here is my code a little bit simplified because of the linking with CoreData:
ViewModel:
extension EditReminderView {
class ViewModel: ObservableObject {
@Published var weekDays: [WeeklyReminder] = []
@Published var reminderType = "daily"
func save() {
// here I update my weekdays for example
}
}
}
Then In the view
struct EditReminderView: View {
@StateObject private var viewModel: ViewModel()
var body: some View {
NavigationView {
Form {
Picker("", selection: $reminderType) {
Text("Daily").tag("daily")
Text("Weekly).tag(weekly)
}
ForEach(viewModel.weekDays.indices, id: \.self) { index in
NavigationLink {
WeeklySingleDayEditView(weekday: $viewModel.weekDays[index])
} label: {
VStack(alignment: .leading) {
Text(viewModel.weekDays[index].dayOfTheWeekStr)
ScrollView(.horizontal) {
HStack {
ForEach(viewModel.weekDays[index].times.indices, id: \.self) { index2 in
SmallCardView(string: viewModel.weekDays[index].times[index2])
}
}
}
}
}
}
.onDelete(perform: delete)
}
..onDisappear(perform: viewModel.save)
}
}
}
Now if I want to change the reminderType
I would have to go to a navigation link to choose from the options, when the picker shows it imeddiatly disappears. Same for the navigation links unless I have other condition in my save function to make sure that no navigation link is active.