SwiftUI: How can I get the selected row in a List before pushing another view
Alright, I found a not too shady solution.
I used this article https://ryanashcraft.me/swiftui-programmatic-navigation shout out to him!
Instead of using a NavigationLink
button, I use a regular button, save the selected item when the user tap then use NavigationDestinationLink
to push the new view as is self.link.presented?.value = true
.
Works like a charm as of beta 3! I'll update my post if something change in the next betas.
Here's how it could look like:
struct AnotherView : View {
private let link: NavigationDestinationLink<AnotherView2>
@State var viewModel = AnotherViewModel()
init() {
self.link = NavigationDestinationLink(
AnotherView2(),
isDetail: true
)
}
var body: some View {
NavigationView {
VStack {
List(viewModel.items.identified(by: \.id)) { item in
Button(action: {
// Save the object into a global store to be used later on
self.viewModel.selectedItem = item
// Present new view
self.link.presented?.value = true
}) {
Text(value: item)
}
}
}
}
}
}
You can add simple TapGesture
NavigationLink(destination: ContentView() ) {
Text("Row")
.gesture(TapGesture()
.onEnded({ _ in
//your action here
}))
}