如何在 SwiftUI MapKit iOS 17 中选择标记?

问题描述 投票:0回答:1

我有一个名为

CustomMarker
的结构,它符合 hashable:

struct CustomMarker: Identifiable, Hashable {
var id: String
var title: String
var location: CLLocationCoordinate2D
var category: String
var notes: String


func hash(into hasher: inout Hasher) {
    hasher.combine(id)
    hasher.combine(title)
    hasher.combine(location.latitude)
    hasher.combine(location.longitude)
    hasher.combine(category)
    hasher.combine(notes)
}

static func ==(lhs: CustomMarker, rhs: CustomMarker) -> Bool {
    return lhs.id == rhs.id &&
        lhs.title == rhs.title &&
        lhs.location.latitude == rhs.location.latitude &&
        lhs.location.longitude == rhs.location.longitude &&
        lhs.category == rhs.category &&
        lhs.notes == rhs.notes
}

}

然后我有一系列标记:

    @State private var markers: [CustomMarker] = [CustomMarker(id: "1", title: "First Marker", location: CLLocationCoordinate2D(latitude: 345, longitude: 235), category: "My Category", notes: "My Notes")]

然后我在地图中显示我的标记:

Map(selection: self.$selectedMarker) {
                    
    UserAnnotation()
                    
    ForEach(self.markerManager.markers) { marker in
        Marker(marker.title, coordinate: marker.location)
            .tag(marker)
            .tint(self.categoryManager.categories.first(where: {$0.name == marker.category})?.pinColor ?? Color(hex: "FFFFFFC57C108"))
    }
                    
}
.mapControls {
MapCompass()
MapUserLocationButton()
MapScaleView()
}

根据我的理解,标签应该选择标记并展开标记图钉,如本视频所示: https://youtu.be/_-x24ng9moA?si=4tqAIWURBAwnfPjP&t=227

到目前为止,当我点击标记时,它没有执行任何操作。

感谢任何帮助,提前致谢:)

swift swiftui mapkit
1个回答
0
投票

由于您的

CustomMarker
id 是
String
,请尝试以下方法:

 @State private var selectedMarker: String? // <--- here
 
 var body: some View {
     VStack {
         Text(selectedItem?.description ?? "no selection") // <--- for testing
         Map(position: $cameraPosition, selection: $selectedMarker) {
             ForEach(markerManager.markers) { marker in
                 Marker(marker.title, coordinate: marker.location)
                     .tag(marker.id) // <--- here
             }
         }
     }
 }
© www.soinside.com 2019 - 2024. All rights reserved.