Given an example as below, I would like to be able to tell if the user has clicked the search bar and it is active. I'm wanting to do this for performance reasons, SwiftUI lists are horribly laggy when the first character is entered on a huge list (yes, I already know the .id(UUID())
trick, still laggy). I would like the list to be empty as soon as the search becomes active.
For the iPhone that would typically mean the keyboard is visible, but that's not reliable, the keyboard could be active for another reason or we could be on an iPad with a physical keyboard.
The EditMode
has an environment variable to tell if the user is currently editing the list but I can't find anything similar for the search bar. Does something like that exist or is there a workaround to detect it?
import SwiftUI
import LoremSwiftum
let words = Lorem.words(50000).components(separatedBy: " ")
struct ContentView: View {
@State var searchText = ""
var searchedWords: [String] {
//I would like something like !searchActive ? words : ...
searchText.isEmpty ? [] : Array(words.filter { $0.localizedCaseInsensitiveContains(searchText) }.prefix(50))
}
var body: some View {
NavigationView {
List {
ForEach(searchedWords.indices, id:\.self) { i in
Text(searchedWords[i])
}
}
.id(UUID())
.searchable(text: $searchText, placement: .navigationBarDrawer(displayMode: .always))
}
}
}
So the environment value is isSearching. Not exactly easy to use since the declaration of the property must be in a subview of the view that is searchable.