In case anyone is wondering how to fix this issue I describe what is happening and how I worked around it.
When a user is submitting their input from a searchable view the searchable view will display an empty input field. However, the value bound to the view still has the value, the user submitted, it is just not displayed. This seems to be a bug in SwiftUI. I worked around it by first setting the bound value to an empty String, waiting a short period of time and the setting the value to the previous user input again.
import SwiftUI
struct SomeView: View {
@State private var searchExpression = ""
@State private var temporarySearchExpression = "" // a new state to temporarily hold the search expression
@State private var isPresented = false
init() {
}
var body: some View {
NavigationStack {
VStack {
Text("some view")
.searchable(text: $searchExpression, isPresented: $isPresented)
.onSubmit(of: .search) {
isPresented = false
temporarySearchExpression = searchExpression
searchExpression = ""
// Waiting for a short period of time is necessary.
// It seems SwiftUI needs some time to process the state changes.
DispatchQueue.main.asyncAfter(deadline: .now().advanced(by: DispatchTimeInterval.milliseconds(1))) {
searchExpression = temporarySearchExpression
}
}
}
}
}
}
#Preview {
SomeView()
}