繁体   English   中英

如何使整个MKPinAnnotationView可以轻敲,而不仅仅是正确的附件视图

[英]How to make a whole MKPinAnnotationView tappable, not just right accessory view

在以下MKMapViewDelegate方法中:

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {

    let pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "")
    pinAnnotationView.rightCalloutAccessoryView = UIButton(type: .DetailDisclosure)
    pinAnnotationView.canShowCallout = true

    return pinAnnotationView
}

如果我像上面那样做,则可以轻按整个视图:

在此处输入图片说明

除此以外:

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {

        let pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "")
        let accessoryView = UIButton(frame: CGRectMake(0, 0, 25, 25))
        accessoryView.setImage(UIImage(named: "icon-menu"), forState: .Normal)

        pinAnnotationView.rightCalloutAccessoryView = accessoryView
        pinAnnotationView.canShowCallout = false

        return pinAnnotationView
}

只能点击正确的附件视图,为什么?

问题是。 如何使整个MKPinAnnotationView可以轻MKPinAnnotationView而不只是正确地公开?

我仍在寻找为什么在第一个代码块中可以使用完整的标注视图,而在第二个代码块中却无法使用。

我找到了如何使整个MKPinAnnotationView标注视图可点击的答案。

基本上,我们可以通过两种方法来实现。

1.使用常规方法。

在这里,我正在为rightCalloutAccessoryView使用图像,但是在声明按钮时有很小的变化,如下所示。

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
    let reuseIdentifier = "pin"
    var pin = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseIdentifier) as? MKPinAnnotationView
    if pin == nil {
        pin = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseIdentifier)
        pin!.pinTintColor = UIColor.redColor()
        pin!.canShowCallout = true
        let button = UIButton(type: .DetailDisclosure)
        button.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
        button.setBackgroundImage(UIImage(named: "img.png"), forState: .Normal)
        pin!.rightCalloutAccessoryView = button
    } else {
        pin!.annotation = annotation
    }
    return pin
}

在这里,在声明按钮的同时,我将其指定为DetailDisclosure类型。

2.第二种方法是使用UITapGestureRecognizer

在这里,我实现了两个标注委托方法,如下所示。

//called when select an annotation
func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) {
    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapped))
    view.addGestureRecognizer(tapGestureRecognizer)
}
//Called when deselects the annotation
func mapView(mapView: MKMapView, didDeselectAnnotationView view: MKAnnotationView) {
    view.removeGestureRecognizer(view.gestureRecognizers!.first!)
}
func tapped(sender: UITapGestureRecognizer) {
    if let view = sender.view as? MKAnnotationView {
        performSegueWithIdentifier("info", sender: view)
        //do yours
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM