Home > Software design >  Make NavigationView searchable but only for one page in the TabView
Make NavigationView searchable but only for one page in the TabView

Time:06-14

I have a NaviagtionView with a TabView and 4 TabItems inside. One of the TabItems should display a searchbar. I can make the NavigationView .searchable but I only want that inside the on TabItem where I want to do the search. How can i do that? Here is my code:

var body: some View {
    NavigationView {
        
        TabView{
            HomeScreen()
                .background(Color("BackgroundColor"))
                .tabItem{
                    Image(systemName: "house")
                }
            PostScreen()
                .background(Color("BackgroundColor"))
                .tabItem{
                    Image(systemName: "plus")
                }
            SearchScreen()
                .background(Color("BackgroundColor"))
                .tabItem{
                    Image(systemName: "magnifyingglass")
                }
            ProfileScreen()
                .background(Color("BackgroundColor"))
                .tabItem{
                    Image(systemName: "person")
                }
        }
        .navigationTitle("MyApp")
        .navigationBarTitleDisplayMode(.inline)
       .searchable(text: $text)
        
        
    }
}

CodePudding user response:

Found a way, add an extension:

extension View {
@ViewBuilder func `if`<Content: View>(_ condition: Bool, transform: (Self) -> Content) -> some View {
    if condition {
        transform(self)
    } else {
        self
    }
}

}

and then use it like this:

.if(selectedTab == "search") { view in
                        view.searchable(text: $search)
                    }
    }

CodePudding user response:

Just place it to the view you want to be searchable (or even inside), like

        SearchScreen()
            .searchable(text: $text)        // << here !!
            .background(Color("BackgroundColor"))
            .tabItem{
                Image(systemName: "magnifyingglass")
            }
        ProfileScreen()
            .background(Color("BackgroundColor"))
            .tabItem{
                Image(systemName: "person")
            }
    }
    .navigationTitle("MyApp")
    .navigationBarTitleDisplayMode(.inline)
  • Related