Reputation: 43
I'm unsure if SwiftUI .searchable
modifier is intended to offer this functionality, but I saw some tutorials in which the search bar will first appear when you pull down the List.
So far, I found no way to get this to work. My search bar is always visible from the beginning, but I want to let it appear when you scroll the list.
Here is my demo code - which will always show the search bar. Is there any way to hide it at the initial start?
Here is the full code
import SwiftUI
struct ContentView: View {
let names = ["Holly", "Josh", "Rhonda", "Yvonne", "Lucy", "Tim", "Steve", "Sandy", "Bob", "Brian"]
@State private var searchText = ""
var body: some View {
NavigationStack {
List(searchResults.indices, id: \.self) { index in
Text("\(searchResults[index])")
}
.searchable(text: $searchText)
}
.navigationBarTitleDisplayMode(.inline)
}
var searchResults: [String] {
if searchText.isEmpty {
return names
} else {
let filteredNames = names.filter { $0.contains(searchText) }
return filteredNames.isEmpty ? names : filteredNames
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Any help would be greatly appreciated!
Upvotes: 3
Views: 2683
Reputation: 285200
My search bar is always visible from the beginning
… because you attached it to the navigation stack.
Attach it to the List
var body: some View {
NavigationStack {
List(searchResults.indices, id: \.self) { index in
Text("\(searchResults[index])")
}
.searchable(text: $searchText)
.toolbar {
ToolbarItem() {
Button("Test", action: {})
}
}
.navigationTitle("Content")
}
.navigationBarTitleDisplayMode(.inline)
}
Upvotes: 2