如何使用XIB创建自定义的MKAnnotationView

4

我希望拥有一个自定义的MKAnnotationView。我已经在IB中创建了一个xib文件,并将其类设置为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")

的意思是设置标注视图的图像为名为“Delivery”的图片。

&

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

这些代码只是为了检查代码是否正常工作,并在地图上显示样本视图,因为它们使用从 MKAnnotationView 继承的标准属性。

我不知道如何使 viewFor annotation 方法使用我创建的 XIB。有人可以帮助我吗?我搜索了解决方法,但只找到了一些与 Obj C 相关的内容。

谢谢!

3个回答

3

1- 创建一个名为CallView的xib文件,作为UIView的子类视图。

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)

通过这种方式,您会遇到视图大小的问题。 - Vyachaslav Gerchicov

1
根据Sh-Khan的答案更新了代码库。
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
**Create Custom MKPointAnnotation Class**

import UIKit
import MapKit

    class CustomPointAnnotation: MKPointAnnotation {
       var id : Int
       var url : String

      init(id : Int , url : String ) {
      self.id = id
       self.url = url

}
    }

创建MarkerView类的Xib以用于注释视图的展示。
class MarkerView: MKAnnotationView {
    @IBOutlet weak var imgVwUser: UIImageView!



     init(annotation: CustomPointAnnotation?, reuseIdentifier: String?) {
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        let hitView = super.hitTest(point, with: event)
        if (hitView != nil)
        {
            self.superview?.bringSubviewToFront(self)
        }
        return hitView
    }
    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        let rect = self.bounds
        var isInside: Bool = rect.contains(point)
        if(!isInside)
        {
            for view in self.subviews
            {
                isInside = view.frame.contains(point)
                if isInside
                {
                    break
                }
            }
        }
        return isInside
    }
}

在您的ViewController中添加MKMapView代理
extension YourViewController : MKMapViewDelegate {

    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 = "MarkerView"
            let viewFromNib = Bundle.main.loadNibNamed(nibName, owner: self, options: nil)?.first as! MarkerView
            var annotationView: MarkerView?

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

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

                // if no views to dequeue, create an Annotation View
                let av = MarkerView(annotation: annotation as? CustomPointAnnotation, 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 = false                                    // callout bubble


                if let annotation =  annotation as? CustomPointAnnotation {


                    annotationView.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
                    annotationView.frame = CGRect(x: 0, y: 0, width: 66, height: 75)

                    let customView = annotationView.subviews.first as? MarkerView
                    customView?.frame = annotationView.frame
                    let image = annotation.url

                    let imageUrl = URL(string: image)


                    customView?.imgVwUser.sd_setImage(with: imageUrl, placeholderImage:  UIImage(named:"defaults"), options: [.refreshCached], completed: nil)


                }
            }

            return annotationView
        }
    }




     }

在地图视图中添加注释

extension YourViewController  {

    func addAnnotation(){

        let annotationsToRemove = mapView.annotations.filter { $0 !== mapView.userLocation }
        mapView.removeAnnotations( annotationsToRemove )

        var annotations: [CustomPointAnnotation] = []

        for  i in 0..<self.arrayData.count {


            let customPoints = CustomPointAnnotation.init(id: arrayData[i].id  ?? 0, url:  arrayData[i].url)


            let location = CLLocationCoordinate2DMake(self.arrayData[i].lat ?? 0, self.arrayData[i].lng ?? 0)
            customPoints.coordinate = location

            annotations.append(customPoints)
        }

        mapView.addAnnotations(annotations)

    }


}

  1. 注释视图的框架变成了零,您必须手动设置它,这已经意味着存在一个错误;
  2. 在选择时,注释开始轻微跳动。被踩了。
- Vyachaslav Gerchicov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接