gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 01:00:06 25 4
gpt4 key购买 nike

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

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

annView.setNeedsDisplay()

这就是您所需要的一切。

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

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

关于ios - 如何在更改为自定义 MKAnnotation 数据后更新自定义 MKAnnotationView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35495414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com