Is it OK to use closure, wrapped in a Binding in SwiftUI? Or does it have any downsides? It looks like it's working fine, and I find it useful at times, but I don't see such things in any articles or examples. Are there any reasons to avoid it?
Why would one want to use a binding to a closure? Two real-word examples:
- I have a
SelectLocationScreenwhere user search for a location. I need a map region to support the search, but it's located inside a subviewMapViewwhich is a wrapper aroundMKMapView(can't use vanillaMapViewdue to iOS 15 deploy target). I tried to use a binding to actualMKCoordinateRegion, but turns outMKMapViewupdates it so frequently it makes my interface unresponsive. Since I need map region only when a user submits the search I settled on binding to a closure.
struct SelectLocationScreen: View {
@State private var getMapRegionClosure: () -> MKCoordinateRegion = { .default }
...
}
struct MapView: UIViewRepresentable {
@Binding var getMapRegionClosure: () -> MKCoordinateRegion
...
}
- The same
SelectLocationScreenhas a search bar and I need to do something if user taps on the submit button. The problem isonSubmit(of: .search)works only where.searchableis defined (i.e. inSelectLocationScreen), but I need to handle the tap in a child view. So again, I use binding to a closure.
struct SelectLocationScreen: View {
@State private var submitSearchHandler: (String) -> Void = { _ in }
...
var body: some View {
...
.searchable(text: $query, prompt: "...")
.onSubmit(of: .search) { submitSearchHandler(query) }
}
}
private struct SearchResultsOverlay: View {
@Binding var submitSearchHandler: (String) -> Void
...
var body: some View {
...
.onFirstAppear {
submitSearchHandler = { /* fire MKLocalSearch */ }
}
}
}