我需要将点击侦听器添加到所有注释视图。该侦听器打开另一个视图控制器。 我写了这段代码:
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
if let selected = (view.annotation as? CustomAnnotation) {
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapped(sender:)))
view.addGestureRecognizer(tapGestureRecognizer)
self.selectedAnnotation = selected
}
}
@objc func tapped(sender: UITapGestureRecognizer)
{
if let controller = DetailsController.storyboardInstance(){
if let selectedAnnotation = selectedAnnotation{
controller.selectedAnnotation = selectedAnnotation
mapView.deselectAnnotation(selectedAnnotation, animated: false)
}
self.present(controller, animated:true, completion:nil)
}
}
tapped
侦听器打开另一个视图控制器。但是,当我关闭该视图控制器时,仍会选择MkAnnotationView。如何关闭?还有其他方法可以将回调添加到所有MkAnnotationView吗?
答案 0 :(得分:0)
使用MKAnnotationView.setSelected(_:animated:)
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
...
view.setSelected(false, animated: false)
}
或MKMapView.deselectAnnotation(_:animated:)
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
if let selected = view.annotation as? CustomAnnotation {
...
mapView.deselectAnnotation(selected, animated: false)
}
}
Update-1
if let annotationView = mapView.view(for: selected) {
annotationView.setSelected(false, animated: false)
}
答案 1 :(得分:0)
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
if view.annotation is MKClusterAnnotation
{
view.setSelected(false, animated: false)
return
}
customview = UINib(nibName: "CustomViewForAnnotation", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! CustomViewForAnnotation
customview.initialize(textForCell: "Spacious #3BHK #Flat sale in ABA Cleo County #Sector121 #Noida 201307 #Apartment #ForSale #Residential #Property", placeName: "fgfvf", cellCount: 2)
customview.loadCell(customview)
view.addSubview(customview)
}
func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) {
customview.removeFromSuperview()
}