I have a navigation link and I need a different behavior when its label (MyView
) is tapped depending on the edit mode (or any other condition):
- If we are not in edit mode, I want to trigger the navigation link and show the
DetailView
with the selected model. - If we are in edit mode, I don’t want to trigger the navigation link and show an
EditingView
in a modal sheet instead.
Here’s a way to implement this that I came up with:
NavigationLink(tag: model, selection: $displayedItem) {
DetailView(model: model)
} label: {
if editMode == .active {
MyView()
.onTapGesture {
editingModel = model
}
} else {
MyView()
}
}
.sheet(item: $editingModel) { model in
EditingView(model: model)
}
The problem with this approach is that the views in the if- and the else-branch have not the same type (due to the onTapGesture
modifier) and SwiftUI doesn’t recognize them as the same view. Thus, animations cannot be interpolated and don’t work properly. Also, MyView
always loses its state each time editMode
is toggled.
(Here’s a great explanation from Chris Eidhof on why that happens: https://www.objc.io/blog/2021/08/24/conditional-view-modifiers/)
So I went ahead and moved the if-statement inside the onTapGesture
modifier as follows so that I don’t have two different MyView
s:
NavigationLink(tag: model, selection: $displayedItem) {
DetailView(model: model)
} label: {
MyView()
.onTapGesture {
if editMode == .active { // moved
editingModel = model
} // moved
}
}
}
.sheet(item: $editingModel) { model in
EditingView(model: model)
}
Problem with this is that now requirement #1 doesn’t work anymore: The onTapGesture
completely swallow the tap gesture and thus the navigation link is never trigged to show the DetailView
. Makes sense.
Now my question is:
4
Answers
Building on George's suggestion, I ended up with the following custom modifier:
Works like a charm and this way, I don't have to specify the same condition
editMode == .active
twice (single source of truth). Highly recommended. 😉In short, you want to change:
Into:
This fixes the issue because now the
onTapGesture
is only triggered when it can actually listen to touches. It can only trigger wheneditMode == .active
, because otherwise the hit testing is disabled.Full example:
Changing the inner label bit to:
Use Group to wrap onTapGesture. That’s it.
you can use custom modifier.
}