当我点击注释视图和this behavior it's right时,也会调用我的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
}
}
}
答案 0 :(得分:2)
要实现它,您需要为正确的附件视图添加目标。您可以通过将按钮设置为 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 {
}
答案 1 :(得分:1)
使用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无法点击。
当您点按calloutAccessoryControlTapped
或直接点按MKAnnotationView
rightCalloutAccessoryView
3.如果你有一个leftCalloutAccessoryView
的UIControl,当你点击它时,你的选择器和calloutAccessoryControlTapped
都会被调用。
4.从iOS 9开始,您可以在MKAnnotationView中使用detailCalloutAccessoryView
。只有当您点击它时,您的选择器才会被调用。
5.此外,您还可以创建自己的自定义MKAnnotationView,并更改其行为。