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?
2
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))
0
I came across a similar requirement in my latest project and I created this simple extension
extension View {
@ViewBuilder
func searchable(_ condition: Bool, text: Binding<String>,placement: SearchFieldPlacement = .automatic,prompt: String) -> some View {
if condition {
self.searchable(
text: text,
placement: placement,
prompt: prompt
)
} else {
self
}
}
}