Can Celik
Can Celik

Reputation: 2087

Search Bar is briefly visible when navigating with NavigationStack (SwiftUI)

I have a .searchable modifier on a list where I navigate to with new NavigationStack. However when the view loads the search box is briefly visible which looks weird. Am I using the navigation stack incorrectly or is this some kind of bug?

Here is an animated gif where a slowed down the animations so it is easy to see it on the List 1.

searchable issue

and here is the code to replicate it.

import SwiftUI

struct ContentView: View {
    var body: some View {
        TabView {
            View1()
                .tabItem {
                    Label("View 1", systemImage: "1.circle")
                }
            
            View2()
                .tabItem {
                    Label("View 2", systemImage: "2.circle")
                }
        }
    }
}

struct View1: View {
    enum Page {
        case listView1
        case listView2
    }
    
    var body: some View {
        NavigationStack {
            List {
                NavigationLink(value: Page.listView1) {
                    Text("List View 1")
                }
                
                NavigationLink(value: Page.listView1) {
                    Text("List View 2")
                }
            }
            .navigationDestination(for: Page.self) { page in
                switch page {
                case .listView1:
                    ListView1()
                case .listView2:
                    ListView2()
                }
            }
            .navigationTitle("View1")
        }
    }
}


struct ListView1: View {
    @State private var search: String = ""
    
    var body: some View {
        List {
            ForEach(1..<20) { i in
                Text("List \(i)")
            }
        }
        .searchable(text: $search)
        .navigationTitle("List View 1")
    }
}

struct ListView2: View {
    var body: some View {
        List {
            ForEach(1..<20) { i in
                Text("List \(i)")
            }
        }
        .navigationTitle("List View 2")
    }
}

struct View2: View {
    var body: some View {
        Text("View 2")
    }
}

Upvotes: 3

Views: 312

Answers (1)

Evgeny K
Evgeny K

Reputation: 3167

I believe it's NavigationStack bug, I can reproduce it, too. As workaround you can switch to legacy NavigationView:

NavigationView {
    List {
        NavigationLink(destination: { ListView1() }) {
            Text("List View 1")
        }
        
        NavigationLink(destination: { ListView2() }) {
            Text("List View 2")
        }
    }
    .navigationTitle("View1")
}

it works fine

Upvotes: 0

Related Questions