thislooksfun / SwiftlySearch

A small, lightweight UISearchController wrapper for SwiftUI

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Updated properties are not propagated correctly into the search bar coordinator

fwcd opened this issue · comments

commented

Consider the following example:

struct MyView {
    @State var searchText: String = ""
    @State var placeholder: String = "abc"

    var body: some View {
        NavigationView {
            Button("Click me") { self.placeholder = "123" }
                .navigationBarTitle("Test \(placeholder)")
                .navigationBarSearch($searchText, placeholder)
        }
    }
}

One would expect that clicking the button correctly changes both the search placeholder and the title. It, however, only changes the title:

image

Thus the issue seems to be with the search bar. Digging a little deeper, I found that while the SearchBar initializer is invoked correctly after the state update, no new Coordinator is instantiated, thus leaving it with outdated values.

A possible solution might be to update the coordinator in

func updateUIViewController(_ controller: SearchBarWrapperController, context: Context) {
controller.searchController = context.coordinator.searchController
controller.hidesSearchBarWhenScrolling = hidesSearchBarWhenScrolling
controller.text = text
if let resultView = resultContent(text) {
(controller.searchController?.searchResultsController as? UIHostingController<ResultContent>)?.rootView = resultView
}
}

I am not sure how idiomatic of a solution that would be though.

Good catch! This is fixed in v1.2.2