首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >获取MKPointAnnotation标题

获取MKPointAnnotation标题
EN

Stack Overflow用户
提问于 2014-09-28 17:16:29
回答 1查看 1.7K关注 0票数 0

我创建了一个MKMapView,其中包含了地图上的几个MKPointAnnotations。当用户单击视图中的UIButton时,我想在日志中打印标题。我怎么能这么做?到目前为止我有这样的想法:

代码语言:javascript
复制
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) {


}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-09-29 02:11:12

在自定义rightButtonTapped方法中,获取对所点击注释的引用的一种简单可靠的方法是使用map视图的selectedAnnotations数组:

代码语言:javascript
复制
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行:

代码语言:javascript
复制
//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)

然后实现委托方法,而不是自定义按钮方法:

代码语言:javascript
复制
func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, calloutAccessoryControlTapped control: UIControl!) {
    println("\(view.annotation.title!)")
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26087459

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档