didSelect for MKAnnotationView没有开火

Jür*_* P. 1 mapkit mkmapview ios mkmapviewdelegate swift

我有麻烦在MapView上选择自定义注释.我尝试了几种方法,没有成功:

  • 使用MKMapViewDelegate的didSelect
  • 使用添加到AnnotationView的UIButton
  • 对ImageView使用UITapGestureRecognizer,它应该用于注释

您可以在下面的代码中找到所有这些方法:

override func viewDidLoad() {
    super.viewDidLoad()
    // some more initialization code

    for item in items {
        let annotation = IdentifiedMKPointAnnotation() // has only one additional property named "id"

        annotation.coordinate = CLLocationCoordinate2D(latitude: item.spots[0].latitude!, longitude: item.spots[0].longitude!)
        annotation.id = i

        self.mapView.addAnnotation(annotation)

        i += 1
    }
}


// MARK: - MapViewDelegate
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    let item = self.items[(annotation as! IdentifiedMKPointAnnotation).id!]

    let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "")
    //annotationView.canShowCallout = false
    //annotationView.isEnabled = false

    let imageView = UIImageView()
    imageView.frame.size = CGSize(width: 40, height: 40)
    imageView.layer.cornerRadius = 20
    imageView.layer.masksToBounds = true
    imageView.af_setImage(withURL: URL(string: item.images.count > 0 ? item.images[0] : item.image!)!)
    imageView.contentMode = .scaleAspectFill

    //let gr = UIGestureRecognizer(target: self, action: #selector(annotationSelected(_:)))
    //imageView.addGestureRecognizer(gr)
    //imageView.isUserInteractionEnabled = true

    //let button = UIButton()
    //button.frame.size = CGSize(width: 40, height: 40)
    //button.setImage(#imageLiteral(resourceName: "play_arrow"), for: .normal)
    //button.addTarget(self, action: #selector(annotationSelected(_:)), for: .touchUpInside)

    annotationView.addSubview(imageView)
    //annotationView.addSubview(button)

    return annotationView
}

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    performSegue(withIdentifier: "showDetail", sender: self.items[(view.annotation as! IdentifiedMKPointAnnotation).id!])

    view.setSelected(false, animated: false)
}

func annotationSelected(_ sender: UIImageView) {
    performSegue(withIdentifier: "showDetail", sender: self.items[((sender.superview as! MKAnnotationView).annotation as! IdentifiedMKPointAnnotation).id!])
}
Run Code Online (Sandbox Code Playgroud)

任何想法,为什么行动不是/没有解雇?

Kos*_*awa 6

如果注释title为空,didSelect则不调用委托.请尝试以下代码.

let annotation = IdentifiedMKPointAnnotation()
annotation.title = "title"
Run Code Online (Sandbox Code Playgroud)


Jür*_* P. 6

刚刚根据以下帖子找到了解决方案:https : //stackoverflow.com/a/28671680/6010489

设置 annotationview 的高度和宽度就足够了:

annotationView.frame.size.height = 40
annotationView.frame.size.width = 40
Run Code Online (Sandbox Code Playgroud)