我创建了一个MKMapView,它在地图上包含几个MKPointAnnotations。当用户在视图中单击UIButton时,我想在日志中打印标题。我怎样才能做到这一点?到目前为止,我有这个:
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if annotation is MKUserLocation {
//return nil so map view draws "blue dot" for standard user location
return nil
}
let reuseId = "pin"
var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView
if pinView == nil {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView!.canShowCallout = true
pinView!.animatesDrop = true
pinView!.pinColor = .Purple
var rightButton: AnyObject! = UIButton.buttonWithType(UIButtonType.DetailDisclosure)
//MapPointAnnotation *point = (MapPointAnnotation*)pinView.annotation;
//rightButton.venue = point.venue;
rightButton.titleForState(UIControlState.Normal)
rightButton.addTarget(self, action: "rightButtonTapped:", forControlEvents: UIControlEvents.TouchUpInside)
pinView!.rightCalloutAccessoryView = rightButton as UIView
}
else {
pinView!.annotation = annotation
}
return pinView
}
func rightButtonTapped(sender: AnyObject) {
}
答案 0 :(得分:0)
在自定义rightButtonTapped
方法中,获取对已点击的注释的引用的简单可靠方法是使用地图视图的selectedAnnotations
数组:
func rightButtonTapped(sender: AnyObject) {
if self.mapView.selectedAnnotations?.count == 0 {
//no annotation selected
return;
}
if let ann = self.mapView.selectedAnnotations[0] as? MKAnnotation {
println("\(ann.title!)")
}
}
(即使selectedAnnotations
是一个数组,地图视图也只允许一次注释"一次选择#34;因此当前选定的注释始终位于索引0处。)
但是,使用自定义按钮方法更好的方法是使用地图视图的calloutAccessoryControlTapped
委托方法。委托方法将您传递的注释视图的引用传递给您,您可以从中轻松获取基础注释。
要使用委托方法,删除自定义方法的addTarget
行:
//Do NOT call addTarget if you want to use the calloutAccessoryControlTapped
//delegate method instead of a custom button method.
//rightButton.addTarget(self, action: "rightButtonTapped:", forControlEvents: UIControlEvents.TouchUpInside)
然后实现委托方法而不是自定义按钮方法:
func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, calloutAccessoryControlTapped control: UIControl!) {
println("\(view.annotation.title!)")
}