How to add a customView xib as annotation in Ios?

血红的双手。 提交于 2019-12-23 05:47:09

问题


when i am using googlemaps all I have to do is

    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

but if i am using MAPKIT, how will I achieve this.? Mycustomview is a xib view file i created.


回答1:


Try to add the object of the nib view to the annotation view like this

 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

  }



回答2:


ok i found the solution

   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
    }


来源:https://stackoverflow.com/questions/47887717/how-to-add-a-customview-xib-as-annotation-in-ios

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!