如何在Ios中添加customView xib作为注释?

问题描述 投票:0回答:2

当我使用谷歌地图时,我所要做的就是

    let marker = GMSMarker()
    marker.position = postions.target
    marker.title = "TEST"
    marker.map = self.mapView
    let myCustomView:CustomView = UINib(nibName: "CustomView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! CustomView
    marker.iconView = myCustomView

但如果我使用MAPKIT,我将如何实现这一目标。 Mycustomview是我创建的xib视图文件。

ios mapkit swift4
2个回答
4
投票

尝试将nib视图的对象添加到注释视图中,如下所示

 func mapView(_ mapView: MKMapView,viewFor annotation: MKAnnotation) -> MKAnnotationView?
{
    if annotation is MKUserLocation == true
    {

        return nil
    }


    let senderAnnotation = annotation as! MyAnnotation

    let pinReusableIdentifier = senderAnnotation.pinColor.rawValue

    var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: pinReusableIdentifier)

    if annotationView == nil
    {

        annotationView = MKAnnotationView(annotation: senderAnnotation,                                                                                                reuseIdentifier: pinReusableIdentifier)
          annotationView!.canShowCallout = true



    }

  let customView = (Bundle.main.loadNibNamed("directOrderView", owner: self, options: nil))?[0] as! directOrderView;

  var calloutViewFrame = customView.frame;
  calloutViewFrame.origin = CGPoint(x:-calloutViewFrame.size.width/2 + 30,y: -calloutViewFrame.size.height);
  customView.frame = calloutViewFrame;

  annotationView?.addSubview(customView)

  return annotationView

  }

0
投票

好的,我找到了解决方案

   func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        if annotation is MKUserLocation
        {
            return nil
        }
        var annotationView = self.mapView.dequeueReusableAnnotationView(withIdentifier: "Pin")
        if annotationView == nil{
            annotationView = AnnotationView(annotation: annotation, reuseIdentifier: "Pin")
            annotationView?.canShowCallout = false
        }else{
            annotationView?.annotation = annotation
            //annotationView?.canShowCallout = true
           // mapView.deselectAnnotation(annotation, animated: true)
           // mapView.selectAnnotation(annotation, animated: true)
        }
        let myCustomView:CustomView = UINib(nibName: "CustomView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! CustomView
        annotationView?.addSubview(myCustomView)
    //    annotationView?.image = UIImage(named: "starbucks")

        return annotationView
    }
© www.soinside.com 2019 - 2024. All rights reserved.