skip to Main Content

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)
        
        
    }
}

2

Answers


  1. Chosen as BEST ANSWER

    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)
    }
    

  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search