1
votes

I followed this tutorial to add a SearchBar on my SwiftUI app: http://blog.eppz.eu/swiftui-search-bar-in-the-navigation-bar/ It basically uses a custom modifier to add the SearchBar into NavigationView:

extension View {
    
    func add(_ searchBar: SearchBar) -> some View {
        return self.modifier(SearchBarModifier(searchBar: searchBar))
    }
}

Since I my NavigationView wrap a TabView, and I only want to show SearchBar in specified tab (e.g. second tab has SearchBar, the others don't). I would like to hide or remove searchBar view but I couldn't find any way to do it. Please help

This is how I wrap NavigationView outside of TabView:

struct MainView: View {
    @ObservedObject var searchBar = SearchBar()
    @State private var selectedTab :Int = 0
    private var pageTitles = ["Home", "Customers","Sales", "More"]
    
    
    var body: some View {
        NavigationView{
            TabView(selection: $selectedTab, content:{
                HomeView()
                    .tabItem {
                        Image(systemName: "house.fill")
                        Text(pageTitles[0])
                    }.tag(0)
                CustomerListView(searchText: searchBar.text)
                    .tabItem {
                        Image(systemName: "rectangle.stack.person.crop.fill")
                        Text(pageTitles[1])
                    }.tag(1)
                SaleView()
                    .tabItem {
                        Image(systemName: "tag.fill")
                        Text(pageTitles[2])
                    }.tag(2)
                
                MoreView()
                    .tabItem {
                        Image(systemName: "ellipsis.circle.fill")
                        Text(pageTitles[3])
                    }.tag(3)
            })
            .add(searchBar, when: selectedTab == 1)            
        }
    }
}


//Compile error: Function declares an opaque return type, but the return statements in its body do not have matching underlying types
    extension View {
        func add(_ searchBar: SearchBar, when: Bool) -> some View {
            if(when == true)
                return self.modifier(SearchBarModifier(searchBar: searchBar))
            else
                return self
        }
    }
1

1 Answers

1
votes

Try to make it view builder (or wrap condition in Group {})

extension View {

    @ViewBuilder
    func add(_ searchBar: SearchBar, when: Bool) -> some View {
        if when == true {
           self.modifier(SearchBarModifier(searchBar: searchBar))
        } else {
           self
        }
    }
}