jonye._.jin
jonye._.jin

Reputation: 871

How to set value to EnvironmentObject from class?

I want to set value to EnvironmentObject from Delegate class.

struct AppleMapView: UIViewRepresentable {
  @EnvironmentObject var mapViewViewModel: MapViewViewModel
  let mapViewDelegate = MapViewDelegate()
  class MapViewDelegate: NSObject, MKMapViewDelegate {
    func mapView(_ mapView: MKMapView, didChange mode: MKUserTrackingMode, animated: Bool) {
     // This is where I want to set value to EnvObj
     **mapViewViewModel.mode = mode**
    }
  }
}

This is what I want to do.

My code gives error

Instance member 'mapViewViewModel' of type 'AppleMapView' cannot be used on instance of nested type 'AppleMapView.MapViewDelegate'

So, I've tried giving reference to delegate class:

MapViewDelegate(vm: mapViewViewModel) This has no compile error, but when I run the code it made errors

A View.environmentObject(_:) for MapViewViewModel may be missing as an ancestor of this view.: file /BuildRoot/Library/Caches/com.apple.xbs/Sources/Monoceros_Sim/Monoceros-39.4.3/Core/EnvironmentObject.swift, line 55 ```

Neither works. How can I fix my code?

Upvotes: 1

Views: 434

Answers (1)

Asperi
Asperi

Reputation: 258441

It works in different way, it needs to make your MapViewDelegate as coordinator for AppleMapView, like below

struct AppleMapView: UIViewRepresentable {
  @EnvironmentObject var mapViewViewModel: MapViewViewModel

    func makeUIView(context: Context) -> MKMapView {
        let mapView = MKMapView()
        mapView.delegate = context.coordinator // << your delegate
        return mapView
    }

    func makeCoordinator() -> MapViewDelegate {
        MapViewDelegate(self)   // << will be created for you
    }

  class MapViewDelegate: NSObject, MKMapViewDelegate {
    var owner: AppleMapView
    init(_ owner: AppleMapView) {
      self.owner = owner
    }
    func mapView(_ mapView: MKMapView, didChange mode: MKUserTrackingMode, animated: Bool) {
       owner.mapViewViewModel.mode = mode // << now you have access to owner props
    }
  }
}

Upvotes: 1

Related Questions