iOS MapKit custom callout with image and text on top of a pin programmatically using swift

萝らか妹 提交于 2019-12-11 06:07:02

问题


I am trying to show a custom call out on top of pin in the map. It is required that I show an image with some text on top of pin as my call out. The code I wrote produces the following output.

However, my desired output looks like this:

How can I achieve my desired output ? Please note that the bubble is an image asset which has to be used, I know how to draw a bubble using CAShapeLayer but that does not accomplish what I want. Here is the code so far.

// methods for Custom annotations

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

        let annotationView = MKAnnotationView(annotation: pin, reuseIdentifier: "UserLocation")
        annotationView.image = UIImage(named: "marker")
        annotationView.canShowCallout = true
        configureDetailView(annotationView: annotationView)

        return annotationView

    }


    func configureDetailView(annotationView: MKAnnotationView) {
        let width = 300
        let height = 200

        let calloutView = UIView()
        calloutView.translatesAutoresizingMaskIntoConstraints = false

        let views = ["calloutView": calloutView]

        calloutView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[calloutView(300)]", options: [], metrics: nil, views: views))
        calloutView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[calloutView(200)]", options: [], metrics: nil, views: views))


        let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: width, height: height))
        imageView.image = UIImage(named: "address_back")

        calloutView.addSubview(imageView)

        annotationView.detailCalloutAccessoryView = calloutView
    }

Please note: I have already seen this post : Customize MKAnnotation Callout View? but it does not accomplish what I want as it draws the bubble instead of using my bubble image. The following repository will give you sample project to work with (draws the shape on the map instead of using image, when you run the project on the bottom right corner you see "Drop pin" tap on that then tap on the pin to see the drawn bubble).

Ready skeleton to use: https://github.com/robertmryan/CustomMapViewAnnotationCalloutSwift

来源:https://stackoverflow.com/questions/57834000/ios-mapkit-custom-callout-with-image-and-text-on-top-of-a-pin-programmatically-u

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