マップ上に様々なユーザーがいて、そのユーザーのアカウント画像をマップ上に表示させようと思っています。mapkitでマップ上に異なった画像のアノテーションを複数置く際に個々のアノテーションの識別するやり方を教えてください。
swift
1class PhotoData { 2 var text: String 3 let coordinate: CLLocationCoordinate2D 4 let photo:UIImage 5 var annotationPoint = MKPointAnnotation() 6 var smallPhoto = UIImage() 7 8 // 初期化時に呼ばれる 9 init(text: String, photo:UIImage, coordinate: CLLocationCoordinate2D) { 10 self.text = text 11 self.coordinate = coordinate 12 self.photo = photo 13 14 self.smallPhoto = resize(photo) 15 self.annotationPoint.coordinate = coordinate 16 self.annotationPoint.title = text 17 } 18 19 func resize(image:UIImage) -> UIImage 20 { 21 let size = CGSize(width: 54, height: 54) 22 UIGraphicsBeginImageContext(size) 23 image.drawInRect(CGRectMake(0, 0, size.width, size.height)) 24 let resizeImage = UIGraphicsGetImageFromCurrentImageContext() 25 UIGraphicsEndImageContext() 26 return resizeImage 27 28 } 29}
PhotoDataというクラスがあります。その中に画像とアノテーションポイントとタイトルが入っています。
以下のfor文のように、アノテーションを複数個置いていきます。
swift
1for data in dataArray 2{ 3 self.mainMap.addAnnotation(data.annotationPoint) 4}
今は個々のアノテーションの画像を変えるために、アノテーションが置くときの処理はアノテーションのタイトルで識別しています。しかしアノテーションのタイトルが同じものがいくつかあった時に、やはり同じ画像が表示されてしまいます。アノテーションのタイトルで識別する以外に、識別できる方法はないでしょうか?
swift
1func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { 2 3 if annotation === mapView.userLocation { // 現在地を示すアノテーションの場合はデフォルトのまま 4 return nil 5 } 6 else { 7 let identifier = annotation.title 8 if let annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(annotation.title!!) { // 再利用できる場合はそのまま返す 9 return annotationView 10 } else { // 再利用できるアノテーションが無い場合(初回など)は生成する 11 let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier!) 12 annotationView.canShowCallout = true 13 for data in dataArray 14 { 15 if data.text == annotation.title!! 16 { 17 annotationView.image = data.smallPhoto 18 data.annotationView = annotationView 19 } 20 } 21 return annotationView 22 } 23 } 24}
あなたの回答
tips
プレビュー