Hello - I am new to Swift so my apologies in advance if this is an easy fix.
I am intrigued by the new .searchable modifier in SwiftUI as this seems like the most logical way to implement search in a SwiftUI-based app (instead of integrating with UIKit etc.)
I tried running the following code
import SwiftUI
struct SearchableView: View {
@State var searchTerm: String = ""
@Environment(\.isSearching)
private var isSearching: Bool
var body: some View {
NavigationView {
Text("\(String(describing: isSearching))")
}.searchable(text: $searchTerm)
}
}
However, the value of isSearching doesn't seem to be changing when I click on the search bar and start typing.
I tried adding @State to the isSearching
variable but this resulted in an error.
I would be very grateful for any suggestions! Thank you
Try the below code:
import SwiftUI
struct ContentView: View {
@State var query: String = ""
var body: some View {
NavigationView {
SearchableView()
}.searchable(text: .constant("Search"))
}
}
struct SearchableView: View {
@Environment(\.isSearching) var isSearching
var body: some View {
if isSearching {
Text("Searching!")
} else {
Text("Not searching.")
}
}
}