swift、mapView、注释视图不会在点击时显示

swift, mapView, annotation view wont show upon tap

我实现了地图视图并为注释创建了简单的数据模型。

大头针显示在地图上,但我仍然无法通过点击任何大头针了解详细信息。

我的代码:

import UIKit
import MapKit

class MapViewController: UIViewController, MKMapViewDelegate {

    @IBOutlet weak var mapView: MKMapView!
    @IBOutlet weak var topView: MapDataView!

    var dummyModel: DummyModel?

    override func viewDidLoad() {
        super.viewDidLoad()

        dummyModel = DummyModel()

        mapView.delegate = self
        mapView.showsUserLocation = true
        let region = MKCoordinateRegionMakeWithDistance(mapView.userLocation.coordinate, 1000, 1000)
        mapView.setRegion(region, animated: true)

        let range = 0..<Int((dummyModel?.objectsArray.count)!)

数组有效且没有 nil:

        for i in range {
            mapView.addAnnotation((dummyModel?.objectsArray[i])!)
        }

我在地图上添加注释的方式:

        mapView.selectAnnotation(mapView.annotations[0], animated: true)
    }

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        print("viewForAnnotation")
        let identifier = "PubMapObject"

        if annotation is PubMapObject {
            var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)

            if annotationView == nil {
                annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
                annotationView!.canShowCallout = true

                let btn = UIButton(type: .detailDisclosure)
                annotationView!.rightCalloutAccessoryView = btn
            } else {
                annotationView!.annotation = annotation
            }

            return annotationView
        }

        return nil
    }

此方法从未调用过,我也不知道为什么。我想问题出在这里,但我找不到它):

    func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
        print("annotationView")
        let pub = view.annotation as! PubMapObject
    }        
}

尝试使用 didSelect 函数而不是 calloutAccessoryControlTapped。

func mapView(_ mapView: MKMapView, didSelect annotationView: MKAnnotationView) { ...

尝试在返回注释视图之前添加注释视图的设置框架 //我的注释 class 并在返回注释视图之前向注释视图提供宽度和高度并将框架提供给

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

if (annotation.isKind(of: MKUserLocation.self)) {
            return nil
        }


 let reuseId = "PubMapObject"
        if (annotation.isKind(of: PubMapObject.self)) {
            let anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
            anView.isEnabled = true
            anView.isUserInteractionEnabled = true
          let btn = UIButton(type: .detailDisclosure)
           btn.frame = CGRect(x: 0, y: 0, width: 50, height: 70)
            anView!.rightCalloutAccessoryView = btn
            anView.frame = CGRect(x: 0, y: 0, width: 50, height: 70)
             return anView
         }

  return nil
}