从 MKMapView 中的注释导航到另一个视图

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

我有一个要从数据库带到 MKMapView 视图的项目列表。我查询 Apple 服务器以将城市和州转换为纬度和经度。所有这些都有效。

我想做的是,当单击注释时,我需要将用户导航到名为 ItemView(item: clickedOnItem) 的视图,然后发送该项目。

这是我的 MKAnnotation:

class ToDoLocationAnnotation: NSObject, MKAnnotation, Identifiable {
    let name: String?
    let coordinate: CLLocationCoordinate2D
    let toDoItem: ToDoItem
    
    init(toDoItem: ToDoItem,
         name: String?,
         coordinate: CLLocationCoordinate2D) {
        self.name = name
        self.toDoItem = toDoItem
        self.coordinate = coordinate
    }
}

我的观点...

struct MapView: UIViewRepresentable {
    var items: FetchedResults<ToDoItem>
    
    init(items: FetchedResults<ToDoItem>) {
        self.items = items
    }
    
    func getCoordinateFrom(location: String, completion: @escaping(_ coordinate: CLLocationCoordinate2D?, _ error: Error?) -> () ) {
        CLGeocoder().geocodeAddressString(location) {
            completion($0?.first?.location?.coordinate, $1)
        }
    }
    
    func makeUIView(context: Context) -> MKMapView {
        return MKMapView(frame: .zero)
    }
    
    func updateUIView(_ view: MKMapView, context: Context) {
        
        let coordinate = CLLocationCoordinate2D(
            latitude: 39.299236, longitude: -76.609383)
        let span = MKCoordinateSpan(latitudeDelta: 2.0, longitudeDelta: 2.0)
        let region = MKCoordinateRegion(center: coordinate, span: span)
        view.setRegion(region, animated: true)
        
        items.forEach({ item in
            if item.completed == false {
                getCoordinateFrom(location: item.location!) { coordinate, error in
                    guard let coordinate = coordinate, error == nil else { return }
                    view.addAnnotation(ToDoLocationAnnotation(toDoItem: item, name: item.location!, coordinate: coordinate))
                }
            }
        })
    }
}

如果我使用标准的 Map() 函数,我可以这样做:

Map(coordinateRegion: $region, annotationItems: locationList.locations ) { item in
    MapAnnotation(coordinate: item.coordinate) {
        NavigationLink(destination: ToDoItemView(item: item.toDoItem)) {
            VStack {
                Image(systemName: "mappin.circle.fill")
                    .font(.title)
                    .foregroundColor(.red)
            }
        }
    }
}

我看到了这篇相关的 SO 帖子:How to navigate to another page with map annotations in swift, it didn't seem to do I was looking for?

swift swiftui mapkit
© www.soinside.com 2019 - 2024. All rights reserved.