检测calloutAccessoryControlTapped只点击rightCalloutAccessoryView
当我点击注释视图时,我的calloutAccessoryControlTapped
也被调用, 这种行为是正确的 。 但是,我如何检测用户是否已经点击了正确的附件视图 (在我的情况下是一个详细的公开按钮) 而不仅仅是在视图中?
我添加了一个简单的检查,但它不起作用。
import UIKit import MapKit extension MapVC: MKMapViewDelegate, CLLocationManagerDelegate { func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { if control == view.rightCalloutAccessoryView { ... // enter here even if I tapped on the view annotation and not on button } } }
要实现它,您需要为正确的附件视图添加目标。 你可以通过设置按钮到rightCalloutAccessoryView来实现它,如代码片段所示。
class MapViewController: UIViewController, MKMapViewDelegate { func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { if annotation is Annotation { let annotationView = AnnotationView(annotation: annotation, reuseIdentifier: "reuseIdentifier") let rightButton = UIButton(type: .DetailDisclosure) rightButton.addTarget(self, action: #selector(didClickDetailDisclosure(_:)), forControlEvents: .TouchUpInside) annotationView.rightCalloutAccessoryView = rightButton } return nil } func didClickDetailDisclosure(button: UIButton) { // TODO: Perform action when was clicked on right callout accessory view. } } // Helper classes. class Annotation: NSObject, MKAnnotation { var coordinate: CLLocationCoordinate2D var title: String? var subtitle: String? init(coordinate: CLLocationCoordinate2D, title: String, subtitle: String) { self.coordinate = coordinate self.title = title self.subtitle = subtitle } } class AnnotationView: MKAnnotationView { }
-
使用UIView和UITapGestureRecognizer而不是UIControl
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { let annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "reuseIdentifier") let gestureView = UIView(frame:CGRect(x: 0,y: 0,width: 20,height: 20)) let gestureRecognizer = UITapGestureRecognizer() gestureRecognizer.addTarget(self, action: #selector(MapViewController.didClickGestureRecognizer(_:))) gestureView.addGestureRecognizer(gestureRecognizer) gestureView.backgroundColor = UIColor.redColor() annotationView.rightCalloutAccessoryView = gestureView return annotationView } func didClickGestureRecognizer(sender:UITapGestureRecognizer) -> Void { print("didClickGestureRecognizer") }
当你单击
rightCalloutAccessoryView
,只会didClickGestureRecognizer
,但是你的calloutAccessoryControlTapped
不能被任何人调用。
2.如果你有一个UIControl作为rightCalloutAccessoryView
,你可以直接点击MKAnnotationView.Otherwise MKAnnotationView无法点击。
当您点击rightCalloutAccessoryView
或直接点击rightCalloutAccessoryView
时,将调用您的selector和calloutAccessoryControlTapped
3.如果您有一个UIControl作为leftCalloutAccessoryView
,当您点击它时,将调用您的选择器和calloutAccessoryControlTapped
。
4.从iOS 9开始,你可以在你的MKAnnotationView中有一个detailCalloutAccessoryView
。只有当你点击它时你的选择器才会被调用。
5.您还可以创建自己的自定义MKAnnotationView,并更改其行为。