Last active
October 19, 2021 23:09
-
-
Save svanimpe/152e6539cd371a9ae0cfee42b374d7c4 to your computer and use it in GitHub Desktop.
SwiftUI ObjectBinding in a UIViewRepresentable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct LotMapWrapperView: View { | |
@EnvironmentObject var store: ParkingStore | |
var body: some View { | |
LotMapView(store: store) | |
} | |
} | |
struct LotMapView: UIViewRepresentable { | |
@ObjectBinding var store: ParkingStore | |
func makeUIView(context: UIViewRepresentableContext<LotMapView>) -> MKMapView { | |
MKMapView() | |
} | |
func updateUIView(_ view: MKMapView, context: UIViewRepresentableContext<LotMapView>) { | |
// This is not getting called when store sends didChange :( | |
print("Update view") | |
print(store.parkingLots.count) | |
} | |
} |
Yes, I believe this is a bug. If you add any class property to the UIViewRepresentable, suddenly the bindings do trigger:
class RandomClass { }
let x = RandomClass()
Maybe late but you can build your own Binding and pass whatever object you need, @EnvironmentObject
or @ObservedObject
.
Looks like @FetchRequest
works well inside UIViewRepresentable (if you are using Core Data)
struct ContentView: View {
@EnvironmentObject var store: Store<AppState, AppAction>
var body: some View {
MapViewRepresentable(state: Binding<AppState>(get: { self.store.state }, set { _ in}))
}
}
struct MapViewRepresentable: UIViewRepresentable {
@Binding var state: AppState
[...]
}
Has anyone found a better solution for this yet? Getting the same results - @Binding
works, @ObservedObject
and @EnvironmentObject
only works with class RandomClass { } let x = RandomClass()
I have had great issues trying to get updateUIView
to call on binding changes on iOS14. The class RandomClass { } let x = RandomClass()
hack works perfectly.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I noticed same thing. @binding works, but I don't want to pass a bunch of individual state vars through. Have you found a solution?