简体   繁体   中英

iOS SwiftUI UIViewRepresentable updateUIView find out which properties actually have changed?

I wondered how to test against which @Binding and @StateObject in the UIViewRepresentable have actually changed when the updateUIView is called?

I'm implementing the MKMapView and don't want to update annotations all the time, only when that StateObject changed.

So I'd love to do something like this:

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
        }
    }
}
    

Updating annotations all the time creates a little hitch for rendering which I'd like to avoid. This is probably a rather general questions on UIViewRepresentables are designed to be used for optimised updating.

The way I've approached this in the past is to store the current value of a property inside my context.coordinator. Then, in updateUIView, you can check the new value against your cached value to see if it's changed. I don't love this solution, but it's the best I've found.

Something like this:

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() {
            // ...
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM