我创建了一个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) {
}发布于 2014-09-29 02:11:12
在自定义rightButtonTapped方法中,获取对所点击注释的引用的一种简单可靠的方法是使用map视图的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是一个数组,但地图视图一次只允许“选择”一个注释,因此当前选定的注释始终位于索引0。)
但是,一个比使用自定义按钮方法更好的方法是使用map视图的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!)")
}https://stackoverflow.com/questions/26087459
复制相似问题