2

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)
        
        
    }
}
sgg1999
  • 63
  • 7

2 Answers2

1

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)
}
burnsi
  • 6,194
  • 13
  • 17
  • 27
sgg1999
  • 63
  • 7
1

searchable work with single child view after NavigationView. So my modification is to remove the parent NavigationView and add NavigationView in the individual View.

Check this answer too

https://stackoverflow.com/a/73180190/4549220

Md Tariqul Islam
  • 2,736
  • 1
  • 20
  • 35