MKMapView MKPointAnnotation tap event not called

白昼怎懂夜的黑 提交于 2019-11-29 11:42:13

Okay I found the solution by myself.

You have to set the annotationViews frame explicitly. If you just set subViews for the view, they will be shown, but the views frame is set to 0, 0 (height, weight). So you just can't tap it, cause the area is 0, 0 as well.

My solution is this, the interesting line is annotationView.frame = CGRect(x: 0, y: 0, width: 67, height: 26). Everything else is the same. Now a click on a annotation calls didSelectAnnotationView.

func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
    if (annotation is MKUserLocation) {
        return nil
    }

    let reuseId = "stationAnnotation"

    let annoStation = DataManager.getStationById(annotation.title!.toInt()!)

    var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
    if annotationView == nil {

        annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
        annotationView.frame = CGRect(x: 0, y: 0, width: 67, height: 26)
        let base = UIView(frame: CGRect(x: 0, y: 0, width: 67, height: 26))
        base.userInteractionEnabled = true

        let imageView = UIImageView(frame: CGRect(x: 2, y: 2, width: 22, height: 22))
        imageView.image = UIImage(named: "zapfsaeule")

        base.layer.cornerRadius = 3.0
        base.clipsToBounds = true
        base.backgroundColor = UIColor.whiteColor()

        var priceLabelBig = UILabel(frame: CGRect(x: 25, y: 0, width: 30, height: 25))
        priceLabelBig.textColor = UIColor.blackColor()
        priceLabelBig.font = UIFont(name: priceLabelBig.font.fontName, size: 15)

        var priceLabelSmall = UILabel(frame: CGRect(x: 55, y: 0, width: 12, height: 15))
        priceLabelSmall.textColor = UIColor.blackColor()
        priceLabelSmall.font = UIFont(name: priceLabelBig.font.fontName, size: 12)

        if let curPrice = annoStation?.getPriceWithSettings().description {
            var stringLength = countElements(curPrice)
            var substringToIndex = stringLength - 1
            priceLabelBig.text = curPrice.substringToIndex(advance(curPrice.startIndex, substringToIndex))
            priceLabelSmall.text = curPrice.substringFromIndex(advance(curPrice.startIndex, substringToIndex))
        }

        base.addSubview(imageView)
        base.addSubview(priceLabelBig)
        base.addSubview(priceLabelSmall)

        annotationView.addSubview(base)
        annotationView.annotation = annotation
    }
    else {
        annotationView.annotation = annotation
    }

    return annotationView
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!