如何在更改为自定义 MKAnnotation 数据后更新自定义 MKAnnotationView?

how to update custom MKAnnotationView after change to custom MKAnnotation data?

有没有办法在更改自定义 MKAnnotation 数据后更新自定义 MKAnnotationView?这是观察员发挥作用的地方吗(以前没用过)。

例如,目前我正在手动执行以下操作:

在我的自定义 MKAnnotation 中更改数据后:

let annView: GCCustomAnnotationView = self.mapView.viewForAnnotation(annotation) as! GCCustomAnnotationView
annView.updateText()  

在我的自定义 MKAnnotationView 中:

func updateText() {
    let gcAnnotation : GCAnnotation = self.annotation as! GCAnnotation
    calloutView.line1.text = gcAnnotation.locality
    calloutView.line2.text = gcAnnotation.sublocality
    calloutView.line3.text = gcAnnotation.name
}

您可以实现 KVO 来观察注释数据的变化。这是 MKAnnotationView class 用来观察 MKAnnotation coordinate 属性 变化的机制。标准 Swift 不使用 KVO,它更像是一个 ObjectiveC 遗留下来的东西,在 Swift 中实现起来有点麻烦。我使用的一个简单解决方案是在注释数据更改时在自定义注释视图上调用 setNeedsDisplay。这导致 drawRect 被调用。在 drawRect 的实现中,您可以轮询注释的数据(就像您在代码片段中所做的那样)以更改视图的外观。

长话短说,当您的数据发生变化时:

annView.setNeedsDisplay()

是您所需要的一切。

然后在 drawRect 子classed MKAnnotationView 实例的实现中调用 updateText 函数:

override func draw(_ rect: CGRect) {
    updateText()
    // etc.
}