【问题标题】:MKAnotation - cannot assign value of typ x to type MKAnnotationMKAnotation - 无法将 typ x 的值分配给 MKAnnotation 类型
【发布时间】:2017-02-15 17:50:51
【问题描述】:

我有一张带有注释的地图,效果很好。我想要一个分段控件来更改注释。

这段代码

annotations = getMapAnnotations()
// Add mappoints to Map
mapInfView.addAnnotations(annotations )

在 ViewDidLoad 中工作,但我在更改 plist 文件以从中获取数据后尝试实现它。 我不明白为什么我无法将类型 ['Stands'] 的值分配给 tupe MKAnnotation?当它在分段控制代码中而不是在 viewdidload 中时。 有没有更好的方法来更改注释?

getannotations()

 func getMapAnnotations() -> [Stands] {
    var annotations:Array = [Stands]()
    print("ANNOTATIONS")
    //load plist file
    var stands: NSArray?
    print("(FILE \(iFile)")
    if let path = Bundle.main.path(forResource:  iFile, ofType: "plist")     {
      stands = NSArray(contentsOfFile: path)
      print(path)
       print(stands)  
    }

//iterate and create annotations
if let items = stands {
  for item in items {
    let lat = (item as AnyObject).value(forKey: "lat") as! Double
    let long = (item as AnyObject).value(forKey: "long")as! Double
    let annotation = Stands(latitude: lat, longitude: long)
    let tit = (item as AnyObject).value(forKey: "title") as! String
    let sub = (item as AnyObject).value(forKey: "subtitle") as! String

    annotation.title = tit   //"\(numb) \(tit)"
    annotation.subtitle = sub

    annotations.append(annotation)
  }
}
return annotations

}

看台类

import Foundation

import MapKit

class Stands: NSObject, MKAnnotation {
  var title: String?
  var subtitle: String?
  var no: Int?
  var latitude: Double
  var longitude:Double

  var coordinate: CLLocationCoordinate2D {
    return CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
  }

  init(latitude: Double, longitude: Double) {
    self.latitude = latitude
    self.longitude = longitude
  }
}

IBAction 代码

@IBAction func annotType(_ sender: Any) {
   let infoChoice = AnnotType(rawValue:  infoSegmentController.selectedSegmentIndex)
    switch (infoChoice!) {
    case .WC:
      iFile = "wc"
    case .Restaurant:
      iFile = "restaurant"
    case .ATM:
      iFile = "atm"
    case .Museums:
      print("Museums")
      iFile = "museums"

}
print("END")
annotations = getMapAnnotations()
// Add mappoints to Map
mapInfView.addAnnotations(annotations )

}

【问题讨论】:

  • 什么 annotations?您分配给它,但是它在哪里/如何声明?您必须在某处拥有var annotations;展示下。 — 另外,请显示您声称此工作的整个viewDidLoad。我敢打赌它不一样。

标签: swift xcode mkannotation


【解决方案1】:

马特是对的。 在 ViewDid 加载中我有

var annotations = getMapAnnotations()

在@IBAction func annotType()中

我有

annotations = getMapAnnotations()

添加 var 再次声明它解决了这个问题。

就在类声明之后,以及我拥有的许多其他变量声明

var annotations:MKAnnotations?

这似乎没有任何意义。我刚刚将其注释掉,该应用程序运行良好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-30
    • 2019-12-03
    • 2017-08-07
    • 2021-03-08
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多