【发布时间】:2017-02-02 22:20:45
【问题描述】:
我的问题和这个类似 Displaying custom multiple pins shows wrong pins for locations 但略有不同,我正在使用 Swift。即使转换后,我也无法解决我的问题。 我有注释,每个注释都有不同的图像。图像是编号的指针。每个注释的详细信息来自一个 plist。标题如“1 个停车场”、“2 个磨坊”等。我在空格前取部分以获得对应于 png 图像的数字。
加载时,所有注释都有正确的图像。如果我平移该区域并返回,图像可以相互交换。似乎是重用的问题,但我看不到解决方案。 getMapAnnotations() 在 viewdidload 中被调用。
func getMapAnnotations() -> [Stands] {
var annotations:Array = [Stands]()
print("ANNOTATIONS")
//load plist file
var stands: NSArray?
if let path = Bundle.main.path(forResource: "stands", ofType: "plist") {
stands = NSArray(contentsOfFile: path)
}
//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 numb = (item as AnyObject).value(forKey: "no") as! Int
annotation.title = "\(numb) \(tit)"
annotation.no = numb
annotations.append(annotation)
}
}
return annotations
}
然后是注解视图
func mapView(_ mapView: MKMapView!, viewFor annotation: MKAnnotation!) -> MKAnnotationView! {
let identifier = "Stand"
var imageI: String?
var imageAn: String?
imageI = annotation.title!
if annotation.isKind(of: Stands.self) {
print("ANNOTATION \(imageI!)")
if let range = imageI?.components(separatedBy: " ") {
var imageII = range[0]
imageAn = "\(imageII).png"
print (imageAn!)
}
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
if annotationView == nil {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier)
//
annotationView?.image = UIImage(named: imageAn! )
annotationView?.canShowCallout = true
annotationView?.layer.zPosition = -1
let btn = UIButton(type: .detailDisclosure)
annotationView?.rightCalloutAccessoryView = btn
} else {
annotationView!.annotation = annotation
}
return annotationView
}
return nil
}
【问题讨论】:
标签: annotations swift3 mkannotationview