iOS 11.x Swift 4.0
了解地图视图并使用此代码创建了一个带有左右附件视图的图钉。
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation {
return nil
}
let reuseId = "pin"
var pav:MKPinAnnotationView?
if (pav == nil)
{
pav = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pav?.isDraggable = true
pav?.canShowCallout = true;
pav?.rightCalloutAccessoryView = UIButton(type: .infoLight)
pav?.leftCalloutAccessoryView = UIButton(type: .contactAdd)
}
else
{
pav?.annotation = annotation;
}
return pav;
}
使用此调用来检测何时按下信息灯和/或联系人添加 UIButtons。但是我很难弄清楚如何分辨哪一个被按下了?此呼叫触发?但是如何判断是左派还是右派呢?
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
print("go figure annotationView (view)")
if (view.rightCalloutAccessoryView != nil) {
print("right (view.rightCalloutAccessoryView)")
}
}
显然这是错误的,但是如何知道是点击了左边还是右边?
尝试以下代码:
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if view.rightCalloutAccessoryView == control {
//right accessory
} else {
// left Accessory
}
}
可以将控件强制转换为UIButton
并检查其类型
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
let btn = control as! UIButton
if(btn.buttonType == .infoLight)
{
// right Accessory
}
else
{
// left Accessory
}
}