Skip to content

Instantly share code, notes, and snippets.

@VAndrJ
Last active November 18, 2024 17:02
Show Gist options
  • Select an option

  • Save VAndrJ/19fae6cad7d012957636ea0d9ddcf260 to your computer and use it in GitHub Desktop.

Select an option

Save VAndrJ/19fae6cad7d012957636ea0d9ddcf260 to your computer and use it in GitHub Desktop.
NavigationStack path clear issue on iOS 18.0+
import SwiftUI
@main
struct TestNavigationSearchApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct ContentView: View {
@State private var path: [String] = []
var body: some View {
NavigationStack(path: $path) {
ExampleView(path: $path, title: "Root")
.navigationDestination(for: String.self) { title in
ExampleView(path: $path, title: title)
}
}
}
}
struct ExampleView: View {
@Binding var path: [String]
let title: String
@State private var text = ""
@State private var isSearchPresented = true
var body: some View {
Text(#"Enter the title and press "search""#)
.navigationBarTitle(title)
.toolbar {
if !path.isEmpty {
ToolbarItem {
Button("Root") {
path.removeAll()
}
}
}
}
.searchable(text: $text, isPresented: $isSearchPresented)
.onSubmit(of: .search) {
path.append(text)
}
}
}
@VAndrJ
Copy link
Author

VAndrJ commented Nov 18, 2024

With only one .searchable:

import SwiftUI

@main
struct TestNavigationSearchApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

enum Destination: Hashable {
    case search
    case result(String)
}

struct ContentView: View {
    @State private var path: [Destination] = []

    var body: some View {
        NavigationStack(path: $path) {
            Button("Search") {
                path.append(.search)
            }
            .navigationDestination(for: Destination.self) { destination in
                switch destination {
                case .search:
                    SearchView(path: $path)
                case let .result(text):
                    ResultView(text: text, path: $path)
                }
            }
        }
    }
}

struct SearchView: View {
    @Binding var path: [Destination]

    @State private var text = ""

    var body: some View {
        Text(#"Enter any string and press "search""#)
            .navigationBarTitle("Search")
            .searchable(text: $text)
            .onSubmit(of: .search) {
                path.append(.result(text))
            }
    }
}

struct ResultView: View {
    let text: String
    @Binding var path: [Destination]

    var body: some View {
        Text(text)
            .toolbar {
                if !path.isEmpty {
                    ToolbarItem {
                        Button("Root") {
                            path.removeAll()
                        }
                    }
                }
            }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment