2016-12-02 19 views
0

我有一张带有2个注释的地图,并且我需要2个不同的图像给他们每个人。如何使用Swift将图像更改为MKAnnotation

我知道如何做一个注释,但我的问题是有两个注释。

这里是我的代码之一:

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { 
     let reuseId = "pin" 

     var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) 


     anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId) 
     anView!.image = nil; 
     anView!.image = UIImage(named:"destinationPin") 


     return anView 

    } 

而且如果任何人都可以,如果你给我解释一下什么是reuseId我会很感激。

在此先感谢

+0

你是什么意思两个注释?两个单独的课程? – sdasdadas

+0

我在地图上有两个针,我希望他们每个人都有不同的图像 –

回答

1

首先,添加注释到地图的时候,你需要区分它们。简单的方法是设置标签值。然后,你可以转到你的逻辑如下:

if annotation.tag == 0 { 
    anView!.image = UIImage(named:"destinationPin") 
} else { 
    anView!.image = UIImage(named:"alternateDestinationPin") 
} 

注MKAnnotation其它属性,如标题和坐标可用于分支你的逻辑。

+0

感谢您的答复,我会尽快检查并让您知道 –

+0

我使用过标题。我假设你把标签作为一般的东西吗? (因为它返回了一个错误,注释没有成员标签) –

+0

是的。在我目前的项目中,我按照adasdadas的建议进行了子类化,并添加了标签值。我忘了我做过这件事时,我发布了答案 –

0

您可以将它们转换为可选项。

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { 
    let reuseId = "pin" 

    var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) 

    if let annotation1 = anView as? FirstAnnotation { 
     annotation1.image = UIImage(named: "first.jpg") 
    } else if let annotation2 = anView as? SecondAnnotation { 
     annotation2.image = UIImage(named: "second.jpg") 
    } 
    return anView 
} 

这有类型安全的好处,而不是依靠自己什么躺在里面tag知识。如果你有两个单独的MKAnnotation类型,你应该将它们分类为两个单独的类。

相关问题