![](/img/trans.png)
[英]How to set @EnvironmentObject in an existing Storyboard based project?
[英]How to set value to EnvironmentObject from 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**
}
}
}
這就是我想要做的。
我的代碼給出錯誤
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 ```
兩者都不起作用。 我該如何修復我的代碼?
它以不同的方式工作,它需要讓你的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.