I have the following view that is used in multiple different places in my app :
var body: some View {
Table(sortedResults, sortOrder: $sortOrder) {
TableColumn("Key", value: \.key)
TableColumn("Type", value: \.value.typeString)
TableColumn("Value", value: \.value.valueString)
}
.searchable(text: $searchString, prompt: "Search for a Key")
.textSelection(.enabled)
}
However, I sometimes don't want it to be searchable
(for example when I know I'm displaying a very short list).
Is there a way to conditionally make Table
searchable?
CodePudding user response:
You can create a simple ViewModifier
struct OptionalSearchableViewModifier: ViewModifier{
let isSearchable: Bool
@Binding var searchString: String
func body(content: Content) -> some View {
switch isSearchable{
case true:
content
.searchable(text: $searchString, prompt: "Search for a Key")
case false:
content
}
}
}
Then replace
.searchable(text: $searchString, prompt: "Search for a Key")
with
.modifier(OptionalSearchableViewModifier(isSearchable: sortedResults.count >= 5, searchString: $searchString))