I found a way to achieve what I meant to achieve, but I don't think it's the best way to do it. However, I haven't found any other solution, so if anyone has any tips, I'd really appreciate it! Hahaha.
import SwiftUI
struct ContentView: View {
@State private var path = NavigationPath() // Manages global navigation
var body: some View {
NavigationStack(path: $path) { // Moves NavigationStack outside of TabView
TabView {
ListView(path: $path)
.tabItem {
Label("List", systemImage: "list.bullet")
}
GreenView()
.tabItem {
Label("Green", systemImage: "leaf.fill")
}
}
.navigationDestination(for: String.self) { value in
if value == "ExtraDetailView" {
ExtraDetailView()
}
}
}
}
}
struct ListView: View {
@State private var selectedItem: String?
@Binding var path: NavigationPath // Receives global navigation
let items = ["Item 1", "Item 2", "Item 3"]
var body: some View {
NavigationSplitView {
List(items, id: \.self, selection: $selectedItem) { item in
Text(item)
.onTapGesture {
selectedItem = item
}
}
.navigationTitle("List")
} detail: {
if let selectedItem = selectedItem {
DetailView(item: selectedItem, path: $path)
} else {
Text("Select an item")
}
}
}
}
struct DetailView: View {
let item: String
@Binding var path: NavigationPath // Uses global navigation
var body: some View {
VStack {
Text("Details of \(item)")
Button("See more details") {
path.append("ExtraDetailView") // Pushes the view on top of the TabView
}
}
.navigationTitle("Details")
}
}
struct ExtraDetailView: View {
var body: some View {
Text("Additional information")
.navigationTitle("More details")
}
}
struct GreenView: View {
var body: some View {
NavigationSplitView {
NavigationLink("Go to YELLOW View", destination: YellowView())
.buttonStyle(.borderedProminent)
} detail: {
YellowView()
}
}
}
struct YellowView: View {
var body: some View {
Color.yellow
.ignoresSafeArea()
.overlay(
Text("Yellow View")
.font(.largeTitle)
.foregroundColor(.white)
)
}
}```