【问题标题】:Swift/iOS MapKit function on MKAnnotation tapMKAnnotation 点击​​上的 Swift/iOS MapKit 功能
【发布时间】:2015-07-03 14:03:45
【问题描述】:

我有一张地图,我已经完美地添加了 12 个注释,我想要的是,当有人点击这些注释时,它会在注释的右侧有一个信息按钮,点击时会显示到地图应用程序中的注释。我已经编写了使用所需坐标打开地图应用程序的函数我只是不确定如何将信息按钮添加到注释并使其在点击时执行该函数。

编辑:我需要在 Swift 中完成。

【问题讨论】:

    标签: ios swift ios8 mapkit mapkitannotation


    【解决方案1】:

    可以使用mapview的ViewForAnnotation方法 如下

    - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
    {
        MKAnnotationView *annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"loc"];
        annotationView.canShowCallout = YES;
        annotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    
        return annotationView;
    }
    

    你也可以添加调用附件视图的方法

    - (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
    {
        [self performSegueWithIdentifier:@"DetailsIphone" sender:view];
    }
    

    这样您可以导航到信息按钮上的方向。

    为 Swift 代码更新

    func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, 
                 calloutAccessoryControlTapped control: UIControl!) {
    
        if control == view.rightCalloutAccessoryView {
            println("Disclosure Pressed! \(view.annotation.subtitle)"
        }
    
    }
    

    您可以将其用于 swift 语言。

    请为 viewforAnnotation 添加此代码:

    func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
            if !(annotation is CustomPointAnnotation) {
                return nil
            }
    
            let reuseId = "test"
    
            var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
            if anView == nil {
                anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
                anView.canShowCallout = true
    
                anView.rightCalloutAccessoryView = UIButton.buttonWithType(.InfoDark) as UIButton
    
            }
            else {
                anView.annotation = annotation
            }
    
    
    
            let cpa = annotation as CustomPointAnnotation
            anView.image = UIImage(named:cpa.imageName)
    
            return anView
        }
    

    确保您已添加“MKMapViewDelegate”

    【讨论】:

    • 谢谢,但我相信上面的代码是用于 Obj-C 的,我正在寻找 swift。
    • 我已添加此代码,它可以工作,但我看不到任何更改或信息按钮?
    • 好吧,我现在收到“使用未声明的类型'CustomPointAnnotation'”错误。只是为了确认一下,我的课程是:课程位置:UIViewController,MKMapViewDelegate { // 代码在这里 }
    【解决方案2】:

    对于 Swift 2,我是这样做的:

    let buttonType = UIButtonType.InfoDark
    barAnnotView?.rightCalloutAccessoryView = UIButton(type: buttonType)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-25
      • 1970-01-01
      相关资源
      最近更新 更多