Reputation: 349
Hey guys i'm really stuck and I have not found an answer for this anywhere , so here we go.
I have a mapView that needs to display multiple mkannotations so I make an array and store there title , sub title etc from a array of "posts" which were users posts that were shared to the map (this code works fine)
@IBOutlet weak var mapView: MKMapView!
var annotations = [MKAnnotation]()
var posts = [Post]() // arr of local post objects
func addPostsToMap(){
mapView.removeAnnotations(annotations)
annotations.removeAll()
for post in posts{
let location : CLLocationCoordinate2D = CLLocationCoordinate2DMake(post.lat, post.lon)
let annotation = PostAnnotation(title: post.userName , subtitle: post.postContent, coordinate: location)
annotations.append(annotation)
}
mapView.addAnnotations(annotations)
}
here is the custom postAnnotation :
class PostAnnotation : NSObject , MKAnnotation{
var title: String?
var subtitle: String?
var coordinate: CLLocationCoordinate2D
init(title : String , subtitle : String , coordinate : CLLocationCoordinate2D) {
self.title = title
self.subtitle = subtitle
self.coordinate = coordinate
}
}
Issue how do i tell which annotation is pressed?? I have found i can deque a custom annotation with a mapkit delegate method , however there is no "indexPath" like a table view , so how am i suppost to tell which one is pressed?
Upvotes: 0
Views: 420
Reputation: 13296
Add an extra field to your PostAnnotation
that is the index of the post in the posts
array.
Then in your implementation of mapView(MKMapView, didSelect: MKAnnotationView)
you just need to get the annotation for the view that was tapped, then use the index to get the post from the array.
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
guard let postAnnotation = view.annotation as? PostAnnotation else {
return
}
let post = posts[postAnnotation.index]
// do something with post
}
Upvotes: 1