I have a view with the searchable modifier. It is always displaying a searchBar and works fine.
I find the searchBar is taking up too much space at the top of the view on an iPhone and since it is not used often, I want to only have a magnifying glass icon in the navigation bar. When the user presses that icon I want to show the search bar and hide it again after it becomes inactive.
Is there anyway to do this with the native searchBar (.searchable) without implementing a custom searchBar?
The view is not a list and I am not looking for the functionality of hiding the searchBar as the user scrolls. I just want to be able to control it's visibility with a button in the navigationBar.
struct SomeView: View {
@Environment(\.dismissSearch) private var dismissSearch
@State var searchString = ""
var body: some View {
NavigationStack {
MyView()
.searchable(text: $searchString, placement: .automatic)
.onSubmit(of: .search) {
// Hide SearchBar
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button {
// Show SearchBar
} label: {
Image(systemName: "magnifyingglass")
}
}
}
}
}
}
At the moment there's no way to show/hide the search bar programmatically in SwiftUI. I think a solution can be found, but it strictly depends on your content view (I mean what you called
MyView). If yourMyViewhas a state that can be moved to a view model, you can easily do something like this:The result is what you'd expect:
But, as I stated above, this solution works depending on your
MyView. In order to help you find a solution, it would be great to have more details about yourMyView.EDIT: another, more complicated, example could be:
The result is:
Depending on your needs, I think you can find a solution.