Assuming I have a deeplink implemented like below. After deeplinking into a detail view of one of the tabviews, when I attempt to deeplink to another detail view while on a detailed view, I am unable to do so as the initial deeplinked detail view does not change. How do I achieve this? Additionally, I am looking for a solution which should still work when the deeplinked view is highly nested than the solution provided below.
import SwiftUI
struct MainView: View {
@State private var activeLink: Int? = nil
var body: some View {
NavigationStack {
TabView {
Tab1View(activeLink: $activeLink)
.tabItem {
Label("Tab 1", systemImage: "1.circle")
}
Tab2View(activeLink: $activeLink)
.tabItem {
Label("Tab 2", systemImage: "2.circle")
}
Tab3View(activeLink: $activeLink)
.tabItem {
Label("Tab 3", systemImage: "3.circle")
}
}
}
}
}
struct Tab1View: View {
@Binding var activeLink: Int?
let items = [Item(dataId: 1, name: "Item 1"), Item(dataId: 2, name: "Item 2")]
var body: some View {
List(items) { item in
NavigationLink(destination: DetailView(data: item), tag: item.dataId, selection: $activeLink) {
VStack {
Text(item.name)
}
}
}
}
}
struct Tab2View: View {
@Binding var activeLink: Int?
let items = [Item(dataId: 3, name: "Item 3"), Item(dataId: 4, name: "Item 4")]
var body: some View {
List(items) { item in
NavigationLink(destination: DetailView(data: item), tag: item.dataId, selection: $activeLink) {
VStack {
Text(item.name)
}
}
}
}
}
struct Tab3View: View {
@Binding var activeLink: Int?
let items = [Item(dataId: 5, name: "Item 5"), Item(dataId: 6, name: "Item 6")]
var body: some View {
List(items) { item in
NavigationLink(destination: DetailView(data: item), tag: item.dataId, selection: $activeLink) {
VStack {
Text(item.name)
}
}
}
}
}
struct DetailView: View {
let data: Item
var body: some View {
Text("Detail view for (data.name)")
}
}
struct Item: Identifiable {
let dataId: Int
let name: String
var id: Int { dataId }
}
@main
struct MyApp: App {
@State private var activeLink: Int? = nil
var body: some Scene {
WindowGroup {
MainView()
.onOpenURL { url in
handleDeepLink(url: url)
}
}
}
func handleDeepLink(url: URL) {
// Parse the URL and update the active link
if let id = Int(url.lastPathComponent) {
activeLink = id
}
}
}
1