This latest lesson from the iOS Foundation course, module 5, from CodeWithChris details how to keep track of which button the user pressed using tag
and selection
, whilst also providing an easy way to drill back to the top of the navigation chain.
In the ViewModel, we create a variable to keep track of the current content. We make it @Published
because the ViewModel is called elsewhere and so the variable becomes available elsewhere. The data type is, in our case, an Int
but it’s optional (it’s ‘nil’ if we’re on the top level of the navigation).
@Published var currentContentSelected:Int?
In the main HomeView navigation link, we add the tag
and selection
modifiers (the selection is a binding $
so that it reflects any changes), thus:
NavigationLink(
destination: ...,
tag: module.id,
selection: $model.currentContentSelected,
label: { ... })
When we require a button to return the user to the top level of navigation, we set the above variable to ‘nil’, thus:
Button(action: {
model.currentContentSelected = nil
...
}, label: {
...
})
The video tutorial throws a lot of new stuff at us as Chris explains how this all works with plenty of demonstrations. I’ve no doubt missed something out here, but hopefully there’s enough to trigger memories of where to look in the future if this doesn’t become clearer as we use it more.