简体   繁体   English

如何从类中为 EnvironmentObject 设置值?

[英]How to set value to EnvironmentObject from class?

I want to set value to EnvironmentObject from Delegate class.我想从 Delegate 类为 EnvironmentObject 设置值。

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 MapViewDelegate(vm: mapViewViewModel)这没有编译错误,但是当我运行代码时它出错了

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它以不同的方式工作,它需要让你的MapViewDelegate作为MapViewDelegate协调AppleMapView ,如下所示

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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