【问题标题】:How to set value to EnvironmentObject from class?如何从类中为 EnvironmentObject 设置值?
【发布时间】:2020-03-19 07:01:50
【问题描述】:

我想从 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**
    }
  }
}

这就是我想做的。

我的代码报错

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

所以,我尝试引用委托类:

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

两者都不起作用。如何修复我的代码?

【问题讨论】:

    标签: ios swift swiftui


    【解决方案1】:

    它的工作方式不同,它需要让您的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
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-27
      • 2020-03-19
      • 2018-10-30
      • 2020-10-07
      • 2021-04-12
      • 2020-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多