SwiftUI Map mixing up annotations

Viewed 213

I've hooked up my Map View to an array of custom Product objects that stores the relevant details for each annotation (custom annotation called MapAnnotationButton). There's a possibility to search and every time a search request has been sent to my backend the response is being converted to Product objects and saved to the array (the previous content of the array is being cleared). Yet, for some reason after the first search my map annotations get mixed up. Every time it search (the same phrase) it gets shuffled. Never on the first time though. I have already checked, but even in the annotation creation block the coordinates and name&other properties match.

import SwiftUI
import MapKit

struct MapView: View {    
    @State var keyword = ""
    @State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 0, longitude: 0), span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1))
    @State var products: [Product] = []
    
    
    var body: some View {
        ZStack(alignment: Alignment(horizontal: .center, vertical: .top), content: {
            Map(coordinateRegion: $region, annotationItems: self.products, annotationContent: { current_item in
                MapAnnotation(coordinate: current_item.location?.CLcoordinates ?? CLLocationCoordinate2D(latitude: 1000, longitude: 1000)) {
                    MapAnnotationButton(item: current_item)
                }
            })
            TextField("Search", text: $keyword, onEditingChanged: { editing in
            }, onCommit: {
                UIApplication.shared.endEditing()
                BackendClient.shared.query(keyword: keyword) { products, success in
                    self.products = products ?? []
                }
            })
        })
    }
}

An explanation I had was that, as the annotation creation block gets called, depending on its content, about 2x - 4x the number of item contained in products, there might be annotations above the correct ones. This would mean that it only appears to be mixed up when in reality it there are just other annotations blocking the correct ones below. Nevertheless, every annotation should actually be on its correct place never allowing for something like this to happen.

I would be more than thankful for you tips and ideas! thanks!

First time searching:

First time searching

Secondtime searching:

Second time searching

1 Answers

There seams to be a bug in the SwiftUI framework as far as I can tell. For some reason views won't get updated if they're in a separate struct. If I copied from MapAnnotationButton directly into the MapAnnotation view block it all worked perfectly fine.

I have already filed a radar.

Thank you for your comments though!

Related