iOS SwiftUI UIViewRepresentable updateUIView找出哪些属性实际上已经更改



我想知道如何测试在调用updateUIView时,UIViewRepresentable中的@Binding和@StateObject实际发生了更改?

我正在实现MKMapView,不想一直更新注释,只有当StateObject更改时。

所以我很想做这样的事情:

struct MapView: UIViewRepresentable
{
@ObservedObject var annotations:MyAnnotations
@ObservedObject var region:MKCoordinateRegion
func updateUIView(_ view: MKMapView, context: Context)
{
if annotations.changed == true
{
// ... update annotations
}

if (region.changed == true
{
// ... update region
}
}
}

一直更新注释会给渲染带来一点麻烦,我希望避免这种情况。这可能是关于UIViewRepresentables的一个相当普遍的问题,它被设计用于优化更新。

我过去处理这个问题的方法是将属性的当前值存储在我的context.cordinator中。然后,在updateUIView中,您可以根据缓存的值检查新值,看看它是否发生了更改。我不喜欢这个解决方案,但这是我找到的最好的解决方案。

类似这样的东西:

struct MapView: UIViewRepresentable
{
@ObservedObject var annotations:MyAnnotations
@ObservedObject var region:MKCoordinateRegion
func updateUIView(_ view: MKMapView, context: Context)
{
if annotations != context.coordinator.cachedAnnotations
{
// ... update view
context.coordinator.cachedAnnotations = annotations
}

if (region != context.coordinator.cachedRegion)
{
// ... update view
context.coordinator.cachedRegion = region
}
}

class Coordinator {
var cachedAnnotations: MyAnnotations
var cachedRegion: MKCoordinateRegion

init() {
// ...
}
}
}

相关内容

最新更新