Как сделать пользовательский MKAnnotationView с XIB - PullRequest
0 голосов
/ 18 декабря 2018

Я хочу иметь собственный MKAnnotationView.Я создал xib-файл в IB и установил для него класс MyAnnotationView.

    class MyAnnotationView: MKAnnotationView {

    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    @IBOutlet weak var textLabel: UILabel!
    @IBOutlet weak var busIcon: UIImageView!

}

Вот как выглядит xib - у него есть textLabel и busIcon:

enter image description here

Я использую метод делегата viewFor annotation для создания представлений для всех аннотаций:

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

        // Don't want to show a custom image if the annotation is the user's location.
        if (annotation is MKUserLocation) {
            return nil
        } else {

            let annotationIdentifier = "AnnotationIdentifier"
            var annotationView: MyAnnotationView?                           


            if let dequeuedAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "AnnotationIdentifier") as? MyAnnotationView {
                annotationView = dequeuedAnnotationView
                annotationView?.annotation = annotation
            } else {

                // if no views to dequeue, create an Annotation View
                let av = MyAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
                av.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
                annotationView = av     
            }


            if let annotationView = annotationView {
                annotationView.canShowCallout = true                        // callout bubble
                annotationView.image = UIImage(named: "Delivery")
                annotationView.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
            }

            return annotationView

        }

    }

annotationView.image = UIImage(named: "Delivery")

&

AnnotationView.frame = CGRect(x: 0, y: 0, width: 40, height: 40)

предназначены только для проверки работоспособности кода и отображения образца карты на карте, поскольку они используют стандартные свойства, унаследованные от MKAnnotationView.

Я не знаю, как заставить метод viewFor annotation использовать созданный мной XIB.Может ли кто-нибудь помочь мне с этим?Я искал решение, но нашел только что-то соответствующее в Obj C.

Спасибо!

Ответы [ 2 ]

0 голосов
/ 22 декабря 2018

ОБНОВЛЕННЫЙ КОД НА ОСНОВЕ Ответ Ш-Хана

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

                //  Don't want to show a custom image if the annotation is the user's location.
                if (annotation is MKUserLocation) {
                    return nil
                } else {

                    let annotationIdentifier = "AnnotationIdentifier"
                    let nibName = "MyAnnotationView"
                    let viewFromNib = Bundle.main.loadNibNamed(nibName, owner: self, options: nil)?.first as! MyAnnotationView
                    var annotationView: MyAnnotationView?

                    // if there is a view to be dequeued, use it for the annotation
                    if let dequeuedAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier) as? MyAnnotationView {

                        if dequeuedAnnotationView.subviews.isEmpty {
                            dequeuedAnnotationView.addSubview(viewFromNib)
                        }
                        annotationView = dequeuedAnnotationView
                        annotationView?.annotation = annotation
                    } else {

                        // if no views to dequeue, create an Annotation View
                        let av = MyAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
                        av.addSubview(viewFromNib)
                        annotationView = av     // extend scope to be able to return at the end of the func
                    }

                    // after we manage to create or dequeue the av, configure it
                    if let annotationView = annotationView {
                        annotationView.canShowCallout = true                                    // callout bubble
                        annotationView.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
                        annotationView.frame = CGRect(x: 0, y: 0, width: 40, height: 40)

                        let customView = annotationView.subviews.first as! MyAnnotationView
                        customView.frame = annotationView.frame
                        customView.textLabel.text = (annotationView.annotation?.title)!
                    }
                    return annotationView
                }
}
0 голосов
/ 19 декабря 2018

1 - Создать подкласс вида UIView с xib скажем CallView

2- Внутри viewforAnnotation

let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "id") 
let customView = Bundle.main.loadNibNamed("CallView", owner: self, options: nil).first! as! CallView
// here configure label and imageView
annotationView.addSubview(customView)
...