Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@svanimpe
Last active October 19, 2021 23:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svanimpe/152e6539cd371a9ae0cfee42b374d7c4 to your computer and use it in GitHub Desktop.
Save svanimpe/152e6539cd371a9ae0cfee42b374d7c4 to your computer and use it in GitHub Desktop.
SwiftUI ObjectBinding in a UIViewRepresentable
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)
}
}
@moverholt
Copy link

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?

@svanimpe
Copy link
Author

svanimpe commented Jul 4, 2019

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()

@franckclement
Copy link

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
      [...]
}

@michalstypa
Copy link

michalstypa commented Mar 26, 2020

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()

@dan-ryan
Copy link

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