1

我尝试用注释制作一个简单的地图,但是当我尝试运行它时,detailCalloutAccessoryView 的图像是相同的,但我确定我放了两个不同的图像,这是怎么发生的?或者有没有人有更好的方法来做到这一点?

   var tripspot:[tripSpot] = [
    tripSpot( title: "1", coordinate: CLLocationCoordinate2DMake(24.149062, 120.684891),  location: "台中市北區一中街", type: "rare",cllocation:CLLocation(latitude: 24.181143,  longitude: 120.593158),image : "025"),
    tripSpot( title: "2", coordinate: CLLocationCoordinate2DMake(24.180407, 120.645086), location:"台中逢甲", type: "rare",cllocation:CLLocation(latitude: 24.180407,  longitude: 120.645086),image : "007")]
   // Build LocationManager
let locationManager = CLLocationManager()


 override func viewDidLoad() {
    super.viewDidLoad()


    // set data
    setupData()

}

func setupData(){
    for aSpot in tripspot {
            //set annotation
            let coordinate = aSpot.coordinate
            let title = aSpot.title
            let type = aSpot.type

            //set annotation
            let tripSpotAnnotation = MKPointAnnotation()
            tripSpotAnnotation.coordinate = coordinate
            tripSpotAnnotation.title = title
            tripSpotAnnotation.subtitle = type
            mapView.addAnnotations([tripSpotAnnotation])



        }
    }
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView?
{
    if annotation.isKindOfClass(MKUserLocation)
    {

        return nil
    }

    var view = mapView.dequeueReusableAnnotationViewWithIdentifier("annotationIdentifier")as? MKPinAnnotationView

    if view == nil
    {
        view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "annotationIdentifier")
        view?.canShowCallout = true
        view?.sizeToFit()
    }
    else{
        view!.annotation = annotation
    }
    for aSpot in tripspot{

        // set pinview
        let detailCalloutAccessoryView = UIImageView(frame: CGRectMake(0, 0, 53, 53))
        detailCalloutAccessoryView.image = UIImage(named: aSpot.image!)
        view?.detailCalloutAccessoryView = detailCalloutAccessoryView

    view?.pinTintColor = pinColor(annotation.subtitle!!)
    }
    return view
    }

感谢您的任何建议。

4

1 回答 1

1

您不应遍历tripSpotin的整个数组viewForAnnotation。此方法适用于特定注释,但编写方式将重复设置(和重置)每个注释的细节附件,使其成为每个aSpotin 的每个图像tripspot,有效地为每个注释提供与最后一个相同的细节附件tripspot(并且这样做效率低下)。

相反,使您的注释成为子类MKPointAnnotation并添加一个属性,以便它知道将哪个图像用于给定注释。如果tripspot是引用类型的数组,您可能只需添加一个属性来引用相关tripspot条目(然后它可以从中识别要显示的图像)。然后,viewForAnnotation应该从您的自定义注释子类中检索该属性,而不是遍历tripspot数组。此外,通过包含对基础tripspot条目的引用,您现在还可以使用“did select detail accessory”例程来知道它与哪个tripspot 相关联,并采取适当的措施。

顺便说一句,我不知道有多少潜在的注释,但是将图像的名称保存在tripspot数组中可能更谨慎,而不是图像本身。图像相对较大,如果您有大量注释,您可能会遇到内存问题。根据需要实例化对象通常更谨慎UIImage,而不是用实际图像填充数组。

于 2016-07-14T19:55:54.723 回答