简体   繁体   中英

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?

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
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM