2015-01-02 37 views
2

我想設置一個圖像,而不是使用MapKit的地圖上的圖釘。我知道我必須設置一個自定義MKAnnotationView。因此,我應該執行以下幾行:自定義MKAnnotationView swift:func mapView什麼都不做

func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! { 
    if !(annotation is CustomPointAnnotation) { 
     return nil 
    } 

    let reuseId = "test" 

    var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) 
    if anView == nil { 
     anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId) 
     anView.canShowCallout = true 
    } 
    else { 
     anView.annotation = annotation 
    } 

    //Set annotation-specific properties **AFTER** 
    //the view is dequeued or created... 

    let cpa = annotation as CustomPointAnnotation 
    anView.image = UIImage(named:cpa.imageName) 

    return anView 
} 

但它在我的代碼中根本不起作用。我複製/粘貼了這個post的所有代碼,將名爲1.png的圖像添加到我的支持文件中。但是地圖顯示一個紅色的別針,而不是1.png圖像。

它看起來像整個mapView功能是無用的。我必須在viewDidLoad中調用它嗎?我應該如何使它被使用?另外,重用ID是什麼?我應該在哪裏打電話?

謝謝你的回答和新年快樂。

+1

您是否在視圖控制器中將'MKMapView'的'delegate'設置爲'self'? – akashivskyy

+0

(或者在Interface Builder中設計這個場景時,將'delegate'設置爲視圖控制器?) – Rob

+0

非常感謝你們!我花了整整一年的時間尋找答案。照片終於出現了。現在是巨大的,但我會看看我是否可以編輯框架。如果沒有,我會編輯圖片本身。謝謝。 –

回答

2

確保MKMapView的委託正確鏈接到實現該方法的ViewController。

你可以在「viewWillAppear」方法中這樣做:mapView.delegate = self;

還是在InterfaceBuilder中: - 確保您的MapKit視圖中選擇 - 轉到「連接檢查」 - 在「奧特萊斯」部分,拖放「委託」屬性到ViewController實現代理方法