Swift - 通过公开按钮将数据从mapkit注释传递到另一个视图

时间:2014-10-24 14:14:14

标签: ios swift annotations mapkit callouts

我有一个带注释的地图,点击图钉后,标注会显示注释标题和公开按钮。当我点击按钮时,会触发segue,然后移动到另一个视图。如何确定单击的注释,或将标题传递给另一个视图。

func mapView(mapView: MKMapView!,
    viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
        if annotation is MKUserLocation{
            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 = .Red

            var calloutButton = UIButton.buttonWithType(.DetailDisclosure) as UIButton
            pinView!.rightCalloutAccessoryView = calloutButton
        } else {
            pinView!.annotation = annotation
        }
        return pinView!
}

func mapView(mapView: MKMapView!, annotationView: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {

    if control == annotationView.rightCalloutAccessoryView {
        performSegueWithIdentifier("Detail", sender: self)
    }
}

由于

2 个答案:

答案 0 :(得分:0)

如果注释标题不同,您可以使用MKAnnotation title annotation属性查找引脚

 annotationView.annotation.title

返回String。将String与差异化进行比较。

tag

中使用pinview属性
pinView!.tag //set tag for each pin in `viewForAnnotation` method

func mapView(mapView: MKMapView!, annotationView: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {

    //get tag here
      if(annotationView.tag == 0){
        //Do for 0 pin
     }

    if control == annotationView.rightCalloutAccessoryView {
        performSegueWithIdentifier("Detail", sender: self)
    }
}

答案 1 :(得分:-1)

尝试将标题保存到NSUserDefaults,然后在新视图中抓取该对象。这是我使用的方法。

 func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, calloutAccessoryControlTapped control: UIControl!) {
    if control == view.rightCalloutAccessoryView{


        println(view.annotation.title) // annotation's title

        let title = view.annotation.title


        NSUserDefaults.standardUserDefaults().setObject(title, forKey: "Title")


        var InfoView = self.storyboard?.instantiateViewControllerWithIdentifier("Spot") as! UIViewController

将标题保存到NSUserDefaults后,您只需抓住新的" InfoView中的对象或您正在调用它的任何内容"像这样let spotTitle = NSUserDefaults.standardUserDefaults().objectForKey("SpotTitle") as! String

希望这有帮助