didSelect for MKAnnotationView 未触发

didSelect for MKAnnotationView not firing

我无法在 MapView 上创建可选的自定义注释。我尝试了几种方法,但都没有成功:

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

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!])
}

知道为什么动作没有t/aren没有触发吗?

如果注释的 title 为空,则不会调用 didSelect 委托。试试下面的代码。

let annotation = IdentifiedMKPointAnnotation()
annotation.title = "title"

刚刚根据以下post找到解决方案:

设置注释视图的高度和宽度就足够了:

annotationView.frame.size.height = 40
annotationView.frame.size.width = 40

出于某种原因,当在 Storyboard 中设置 mapView 的委托时,我遇到了同样的问题(Xcode 10.2,Swift 5.0)。所以这是 不工作:

但是,当我删除连接并改为在代码中执行时,它工作正常:

@IBOutlet weak var mapView: MKMapView!

override func viewDidLoad() {
    super.viewDidLoad()

    mapView.delegate = self
}

一个 Swift 5 个错误?故事板解决方案适用于 Objective-C.