在 MapView (Swift) 中单击 MKPlacemark 时如何调用函数?
How can I call a function when an MKPlacemark is clicked in MapView (Swift)?
每当在我的 MapView 上单击 MKPlacemark 时,我都会尝试执行特定功能。此函数从地标中提取信息并将其显示在单独的视图中。我试过使用
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {}
但这似乎不起作用。我不确定是否必须为每个地标命名,我已避免这样做,因为我已经在名称中显示了位置数据(如我的代码中所示)。任何帮助将非常感激。我的代码:
正在启动地标(这发生了很多次,变量已经被实例化):
let coords = CLLocationCoordinate2DMake(latOfPlace!, lonOfPlace!)
let address = [CNPostalAddressStreetKey: addressStreetKey, CNPostalAddressCityKey: addressCityKey, CNPostalAddressPostalCodeKey: addressPostalCodeKey, CNPostalAddressISOCountryCodeKey: addressISOCountryCodeKey]
let place = MKPlacemark(coordinate: coords, addressDictionary: address)
self.mapView.addAnnotation(place)
你需要在里面设置delegate viewDidLoad
self.mapView.delegate = self
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
guard let ann = view.annotation as? MKPlacemark else { return }
print(ann)
}
每当在我的 MapView 上单击 MKPlacemark 时,我都会尝试执行特定功能。此函数从地标中提取信息并将其显示在单独的视图中。我试过使用
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {}
但这似乎不起作用。我不确定是否必须为每个地标命名,我已避免这样做,因为我已经在名称中显示了位置数据(如我的代码中所示)。任何帮助将非常感激。我的代码:
正在启动地标(这发生了很多次,变量已经被实例化):
let coords = CLLocationCoordinate2DMake(latOfPlace!, lonOfPlace!)
let address = [CNPostalAddressStreetKey: addressStreetKey, CNPostalAddressCityKey: addressCityKey, CNPostalAddressPostalCodeKey: addressPostalCodeKey, CNPostalAddressISOCountryCodeKey: addressISOCountryCodeKey]
let place = MKPlacemark(coordinate: coords, addressDictionary: address)
self.mapView.addAnnotation(place)
你需要在里面设置delegate viewDidLoad
self.mapView.delegate = self
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
guard let ann = view.annotation as? MKPlacemark else { return }
print(ann)
}