首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从类中将值设置为EnvironmentObject?

如何从类中将值设置为EnvironmentObject?
EN

Stack Overflow用户
提问于 2020-03-19 15:01:51
回答 1查看 273关注 0票数 1

我想从Delegate类中将值设置为EnvironmentObject。

代码语言:javascript
复制
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**
    }
  }
}

这就是我想要做的。

我的代码出现错误

代码语言:javascript
复制
Instance member 'mapViewViewModel' of type 'AppleMapView' cannot be used on instance of nested type 'AppleMapView.MapViewDelegate'

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

MapViewDelegate(vm: mapViewViewModel)这没有编译错误,但是当我运行代码时出现了错误

代码语言:javascript
复制
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 ```

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-19 15:30:57

它以不同的方式工作,它需要让你的MapViewDelegate作为AppleMapView的协调器,如下所示

代码语言:javascript
复制
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
    }
  }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60752285

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档