首页 > 解决方案 > 为什么iOS模拟器中默认的mapkit注解没有渲染到地图上

问题描述

我正在使用MKAnnotation协议来帮助在我的 iOS 模拟器地图上显示默认标记注释,但我没有看到它呈现。

这是我DriverAnnotation创建的课程;

class DriverAnnotation: NSObject, MKAnnotation {
    var coordinate: CLLocationCoordinate2D
    var uid: String

    init(uid: String, coordinate: CLLocationCoordinate2D) {
        self.uid = uid
        self.coordinate = coordinate
    }
}

这是使用它的代码,应该在地图上显示标记注释;

    func fetchDrivers() {
        guard let location = locationManager?.location else { return }
        Service.shared.fetchDrivers(location: location) { (driver) in
            guard let coordinate = driver.location?.coordinate else { return }
            let annotation = DriverAnnotation(uid: driver.uid, coordinate: coordinate)
            self.mapView.addAnnotation(annotation)
        }

    }

那么为什么注解没有在 iOS 模拟器地图上渲染呢?我得到的只是当前位置缓慢闪烁的蓝点。

地图注释缺失

标签: iosswiftannotationsmapkit

解决方案


displayPriorityofMKMarkerAnnotationView默认为(.defaultLow尽管's的文档建议它应该默认为)。MKAnnotationViewdisplayPriority.required

所以你想要一个MKMarkerAnnotationView.required然后你想声明一个注释视图类,将它设置为.required

class RequiredMarkerAnnotationView: MKMarkerAnnotationView {
    override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
        displayPriority = .required
    }

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

    override var annotation: MKAnnotation? {
        didSet {
            displayPriority = .required
        }
    }
}

mapView.register(RequiredMarkerAnnotationView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)

推荐阅读