#swift #mapkit #mkpinannotationview
#swift #mapkit #mkpinannotationview
Вопрос:
Я создал карту в своем приложении для iOS с помощью MapKit.
Я добавил свои пин-коды в свой вид с помощью кнопки выноски, которая представляет кнопку детализации во всплывающем окне ввода пин-кода.
На данный момент все хорошо, когда я нажимаю на кнопку detail, я могу напечатать некоторый текст, представить новый контроллер просмотра, но моя проблема в том, что я не могу понять, как я могу узнать, какой пин-код я нажал.
Я могу решить это с помощью заголовка, но для меня это не лучший способ, я предпочитаю использовать свой идентификатор элемента вместо строки.
Если кто-нибудь знает, как я могу добавить свойство «id» к своему пин-коду или использовать свойство subtitle (не показывая его во всплывающем окне), я буду благодарен
Спасибо за вашу помощь.
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation {
return nil
}
let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "customAnnotation")
annotationView.image = UIImage(named: "pin")
annotationView.canShowCallout = true
annotationView.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
return annotationView
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl){
print("OK, item tapped.")
}
Ответ №1:
Вы можете создать подкласс MKPointAnnotation
, чтобы добавить ID
свойство
class CustomPointAnnotation: MKPointAnnotation {
let id: Int
init(id: Int) {
self.id = id
}
}
Использование
let annotation = CustomPointAnnotation(id: INTEGER)
annotation.coordinate = CLLocationCoordinate2D(latitude: DOUBLE, longitude: DOUBLE)
mapView.addAnnotation(annotation)
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if let annotation = view.annotation as? CustomPointAnnotation {
print("Annotation (annotation.id)")
}
}
Вы также можете создать свой собственный класс аннотаций, расширив базовый MKAnnotation
протокол, например:
class CustomAnnotation: NSObject, MKAnnotation {
let id: Int
let coordinate: CLLocationCoordinate2D
init(id: Int, latitude: Double, longitude: Double) {
self.id = id
self.coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
}
Комментарии:
1. Большое вам спасибо! У меня почти получилось, я пропустил оператор if let!! Большое спасибо за ваш ответ! Теперь я в восторге !
![]()