gpt4 book ai didi

ios - 如何从类中为 EnvironmentObject 设置值?

转载 作者:行者123 更新时间:2023-12-01 21:58:44 29 4
gpt4 key购买 nike

我想从 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'

因此,我尝试引用委托(delegate)类:
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 ```

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

最佳答案

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

关于ios - 如何从类中为 EnvironmentObject 设置值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60752285/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com