mapView:viewForでマーカーにボタンを追加したいのですが、うまくいきません。
理想の機能
0. ロングタップで現在地にマーカーを設置 → OK
0. マーカーをタップすると吹き出しが表示 左と右にボタンがある → ❌
0. 左のボタンでマーカーの色が変わる 右のボタンでマーカーを削除 → ❌
下記サイトを参考にまずは、デフォルトのマーカーじゃなくて参考サイトの通りピンで吹き出しを表示させようとしているのですが、うまく表示されません。
参考にしたサイト
[Swift]MapKitのPinカスタムでちょっとハマった話
iOS11 アノテーション クラスタリング
【Swift】detailCalloutAccessoryViewの使い方。ピンの吹き出しをカスタマイズする。
もちろん現在エラーは出ていません。
ピンは緑色になっているので、ここまでは問題ありません。
Swift
1annotationView?.pinTintColor = .green
ここから先のコード自体は問題がないはずです。
表示されないということは、書く場所が間違っているのか、それともなにか足りないものがあるのでしょうか?
Swift
1//左ボタンをアノテーションビューに追加する 2 let leftButton = UIButton() 3 leftButton.frame = CGRect(x: 0, y: 0, width: 160, height: 40) 4 leftButton.setTitle("????", for: UIControlState.normal) 5 leftButton.backgroundColor = UIColor.blue 6 pinView.leftCalloutAccessoryView = leftButton
mapView viewFor全体のコード
Swift
1 let markerView = MKMarkerAnnotationView() 2 3 //選択したアノテーションにボタンを追加する 4 func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { 5 6 if annotation is MKUserLocation { 7 return nil 8 } 9 10 let pinView = MKAnnotationView() 11 pinView.canShowCallout = true 12 13 let pinID = "PIN" 14 var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: pinID) as? MKPinAnnotationView 15 if annotationView == nil { 16 annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: pinID) 17 annotationView?.pinTintColor = .green ⇐ここまではOKって 18 //左ボタンをアノテーションビューに追加する 19 let leftButton = UIButton() 20 leftButton.frame = CGRect(x: 0, y: 0, width: 160, height: 40) 21 leftButton.setTitle("????", for: UIControlState.normal) 22 leftButton.backgroundColor = UIColor.blue 23 pinView.leftCalloutAccessoryView = leftButton 24 25 } else { 26 annotationView!.annotation = annotation 27 } 28 return annotationView 29 } 30 31 //アノテーションをタップした時のメソッド 32 func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { 33 if(control == view.leftCalloutAccessoryView) { 34 //左ボタンがタップされたらアノテーションを青に変える 35 if let pinView = view as? MKPinAnnotationView { 36 pinView.pinTintColor = UIColor.blue 37 } 38 } else { 39 //右ボタンがタップされたらアノテーションを削除する 40 mapView.removeAnnotation(view.annotation!) 41 } 42 }
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。