我想知道如何检测地图上按下了哪个标记。我在地图上有很少的标记,从API下载的标记数组中有Marker类,它包含一些数据。现在我想知道在按下标记后如何将数据发送到下一个VC。将整个Array发送到下一个VC,然后以某种方式通过另一个VC上的数组获取数据是不是很好?
答案 0 :(得分:4)
您可以使用userData
属性存储所需的唯一数据。
for (index,i) in markers.enumerated() {
let marker = GMSMarker()
marker.position = CLLocationCoordinate2DMake(i.lat, i.lng)
marker.userData = ["index": index]
print("@@@\(i.id)")
marker.title = i.name
marker.map = mapView
}
在didTap方法中执行这样的操作。
func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
performSegue(withIdentifier: "details", sender: marker)
return true
}
现在在prepareForSegue
中获取userData
的对象索引。
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "details" {
var nextVC = segue.destination as! VC2
if let marker = sender as? GMSMarker,
let dict = marker.userData as? [String:Int] {
print(dict["index"])
// use this array index to access object from array
}
}
}