如何在更改为自定义 MKA 注释数据后更新自定义 MKA 注释视图



有没有办法在更改为自定义 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 类用来观察MKAnnotation coordinate属性变化的机制。标准 Swift 不使用 KVO,它更像是 ObjectiveC 遗留的东西,在 Swift 中实现有点麻烦。我使用的一种简单解决方案是在批注数据发生更改时在自定义批注视图上调用setNeedsDisplay。这会导致调用drawRect。在drawRect的实现中,您可以轮询批注的数据(就像在代码段中一样)以更改视图的外观。

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

annView.setNeedsDisplay()

是您在这种情况下所需要的一切。

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

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

最新更新