gpt4 book ai didi

ios - UIViewRepresentable.updateUIView(_ :context:) is not called when @State, @Binding 或 @EnvironmentObject 已更改

转载 作者:行者123 更新时间:2023-11-29 13:53:09 25 4
gpt4 key购买 nike

当此 View 及其父 View 所依赖的 ObservableObject 发生更改时,不会调用 UIViewRepresentable.updateUIView。

我有一个带有“@State var locationManager: LocationManager”的 GameView,它作为绑定(bind)传递到我的 MapView。 MapView 符合 UIViewRepresentable 协议(protocol)。 LocationManager 除其他外符合 ObservableObject 并具有以下与一致性相关的代码:

var didChange = PassthroughSubject<locationmanager, Never>()  


var lastKnownLocation: CLLocation {
didSet {

// Propagate the update to the observers.
didChange.send(self)
print("Finished propagating lastKnownLocation to the observers.")
}
}

我想每次 LocationManager.lastKnownLocation 发生变化时,GameView 和 MapView 都必须更新。实际上,当我按主页按钮退出应用程序时,我只会看到 MapView.updateUIView() 被调用。此时控件进入 updateUIView() 并且当我再次打开应用程序时(不是编译安装运行),我得到了更新。这也会在 GameView() 出现后不久发生。

是我对 SwiftUI 工作原理的理解有误还是存在错误?我该如何正确处理?

struct GameView: View { 
@State var locationManager: LocationManager


var body: some View {
MapView(locationManager: $locationManager)
}
}

struct MapView: UIViewRepresentable {

@Binding var locationManager: LocationManager

func makeUIView(context: Context) -> GMSMapView{ ... }

func updateUIView(_ mapView: GMSMapView, context: Context) { ... }

}

class LocationManager: NSObject, CLLocationManagerDelegate, ObservableObject {

var didChange = PassthroughSubject<LocationManager, Never>()

var lastKnownLocation: CLLocation {
didSet {


// Propagate the update to the observers.
didChange.send(self)
print("Finished propagating lastKnownLocation to the observers.")
}
}

...

}

我希望每次 tim LocationManager.lastKnownLocation 发生变化时,都会调用 MapView.updateUIView()。实际上,调用仅在我按主页按钮退出应用程序(并再次进入)时发生

最佳答案

像这样改变 MapView

struct MapView: UIViewRepresentable {
@State var locationManager = LocationManager()

func makeUIView(context: Context) -> GMSMapView{
let view = GMSMapView(frame: .zero)
...
willAppear(context)
return view
}

func updateUIView(_ mapView: GMSMapView, context: Context) { ... }

func makeCoordinator() -> MapView.Coordinator {
return Coordinator()
}

static func dismantleUIView(_ uiView: GMSMapView, coordinator: MapView.Coordinator) {
coordinator.cancellable.removeAll()
}

class Coordinator {
var cancellable = Set<AnyCancellable>()
}
}

extension MapView {
func willAppear(_ context: Context) {
locationManager.didChange.sink{
print("location: \($0)")
}.store(in: &context.coordinator.cancellable)

locationManager.startUpdating()
}
}

我认为这个方法 locationManager.startUpdating(), locationManager.stopUpdating() 需要调用另一个类。

关于ios - UIViewRepresentable.updateUIView(_ :context:) is not called when @State, @Binding 或 @EnvironmentObject 已更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58474377/

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