【问题标题】:how to update custom MKAnnotationView after change to custom MKAnnotation data?更改为自定义 MKAnnotation 数据后如何更新自定义 MKAnnotationView?
【发布时间】:2016-02-19 00:54:41
【问题描述】:

有没有办法在更改自定义 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
}

【问题讨论】:

    标签: ios swift mapkit mkannotation mkannotationview


    【解决方案1】:

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

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

    annView.setNeedsDisplay()
    

    是您所需的一切。

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

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

    【讨论】:

      猜你喜欢
      • 2011-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-30
      • 1970-01-01
      • 1970-01-01
      • 2011-09-17
      • 1970-01-01
      相关资源
      最近更新 更多