在 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
}
如果我像上面那样做,那么整个 View 都是可点击的:
否则:
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
}
只点击了右侧的附件 View ,为什么?
The question is. What to do to make tappable a whole
MKPinAnnotationView
not just its right disclosure?
最佳答案
我仍在寻找为什么它适用于第一个代码块中的完整标注 View ,但不适用于第二个代码块。
我找到了如何使整个 MKPinAnnotationView 标注 View 可点击的答案。
基本上我们可以通过两种方法实现这一点。
<强>1。使用正常方法。
我在这里为 rightCalloutAccessoryView 使用了一张图片,但是在声明 button 时有一些小的变化,如下所示。
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 类型的 Button。
2。第二种方法是使用 UITapGestureRecognizer
我在这里实现了两个 callout 委托(delegate)方法,如下所示。
//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
}
}
关于ios - 如何使整个 MKPinAnnotationView 可点击,而不仅仅是正确的附件 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38589264/