快速标注按钮和 Firestore 的问题

问题描述

我在 Firestore 上有 5 个系列。使用这些集合的文档数据,我创建了不同类型的注释并将它们显示在地图视图上。

问题是我想传递存储在每个注释中的所有信息,并将其显示在另一个视图控制器上,当您按下标注按钮时会出现该信息。

我不知道如何引用我正在按下的注释,然后将数据传递到另一个屏幕。

这是我第一次使用数据库,我没有很多经验,所以我希望得到一些帮助。

谢谢!

解决方法

很难给出具体的答案,因为我不了解您的功能的全部范围。但这就是您通常的做法。

首先,当您创建 MKAnnotation 子类时,您定义了一个属性来保存您可以稍后引用的对象。例如,假设我要在地图中显示餐馆和超市。

class RestaurantAnnotation: NSObject,MKAnnotation {
    let restaurant: Restaurant
    
    var title: String? {
        return restaurant.name
    }
    
    var coordinate: CLLocationCoordinate2D {
        return restaurant.coordinate
    }
    
    init(restaurant: Restaurant) {
        self.restaurant = restaurant
        super.init()
    }
}

struct Restaurant {
    let name: String
    let coordinate: CLLocationCoordinate2D
}

超市也是一样。

然后在创建注释时,将 Restaurant 对象传递给它。

let restaurant = Restaurant(name: "McDonald's",coordinate: CLLocationCoordinate2D(latitude: 27.2831,longitude: -127.831))
let restaurantAnnotation = RestaurantAnnotation(restaurant: restaurant)
mapView.addAnnotation(restaurantAnnotation)

您实现了 mapView(_:annotationView:calloutAccessoryControlTapped:) 委托方法,以便在用户点击注释中的标注按钮时收到通知。在其中,您可以轻松引用之前传递给它的对象。

func mapView(_ mapView: MKMapView,annotationView view: MKAnnotationView,calloutAccessoryControlTapped control: UIControl) {
    if let annotation = view.annotation as? RestaurantAnnotation {
        print(annotation.restaurant)
    } else if let annotation = view.annotation as? SupermarketAnnotation {
        print(annotation.supermarket)
    }
}

之后你可以使用这些数据做任何你想做的事情。在您的情况下,将其传递到新屏幕。