-
|
Taking sample code from Episode 0172, I like how you attach the navigation title and the cancel+save buttons onto the This allows you to attach explicit Cancel and Save actions, which the NavigationLink(
unwrap: self.$viewModel.route,
case: /ItemRowViewModel.Route.edit,
onNavigate: self.viewModel.setEditNavigation(isActive:),
destination: { $itemViewModel in
ItemView(viewModel: itemViewModel)
.navigationBarTitle("Edit")
.navigationBarBackButtonHidden(true)
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button("Cancel") {
self.viewModel.cancelButtonTapped()
}
}
ToolbarItem(placement: .primaryAction) {
HStack {
if self.viewModel.isSaving {
ProgressView()
}
Button("Save") {
self.viewModel.edit(item: itemViewModel.item)
}
}
.disabled(self.viewModel.isSaving)
}
}
}
) {
// ...
}Note: The My question is (still keeping the i.e. so that on swiping back the change is made and not lost. First ideaI had two ideas. The first was to final class ItemRowViewModel: ObservableObject, Identifiable {
private var cancellables = [AnyCancellable]()
func setEditNavigation(isActive: Bool) {
if isActive {
let viewModel = ItemViewModel(item: self.item)
// Save the cancellable
cancellables += [viewModel.$item.sink { [unowned self] item in
self.item = item
}]
self.route = .edit(viewModel)
}
else {
self.route = nil
// Clear the cancellable
cancellables = []
}
}
}This feels a bit awkward to me, though perhaps it's the best way. Second ideaAn alternative could be to add an NavigationLink(
unwrapping: $viewModel.route,
case: /ItemRowViewModel.Route.edit,
onNavigate: { isNavigating in
viewModel.setEditNavigation(isActive: isNavigating)
},
destination: { $itemViewModel in
ItemView(viewModel: itemViewModel)
.navigationTitle("Edit Item")
.onDisappear {
// We don't take the Cancel/Save approach, we want to save the changes immediately:
viewModel.commit(item: $itemViewModel.wrappedValue.item)
}
}
) {
// ...
}with the following inside the func commit(item: Item) {
self.item = item
}However, this visibly updates the ItemRowView as the user pops back - you can see the change get committed in the UI after the pop completes. Just to reiterate, I'm looking to keep Just wondering what would be recommended as the best approach here :) Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
Hi @iandundas, the |
Beta Was this translation helpful? Give feedback.
Hi @iandundas, the
.sinkidea does work, and is in fact what we do it in our Standups demo app. You can see it here.We covered this style in episode #216 at around 38:40.