簡體   English   中英

類的自定義方法符合MKAnnotation協議

[英]Custom method on class that conforms to MKAnnotation protocol

我有一節課:

class MyAnnotion: NSObject, MKAnnotation {

let title: String?
let subtitle: String?
let item: MyCustomItem
let coordinate: CLLocationCoordinate2D

init(customItem: MyCustomItem, currentLocation: CLLocation)  {
    coordinate = item.coordinate
    pageId = "\(item.pageId)"
    title = "\(item.title)"
    item = myCustomItem
}

//TODO: Even though in mapView viewFor: the annotation is a WikiAnnotation, it wont recognize any custom function defined here
func imageUrl() -> String? {
    guard let url = item.imageUrl else {
        return nil
    }
    return url
}
}

當我將注釋加載到地圖中時,我將它們加載為MyAnnotion

mapView viewFor:函數傳遞一個MKAnnotation注釋,但當我檢查它實際上是一個MyAnnotation

麻煩的是,如果我嘗試訪問imageUrl()方法,它告訴我MKAnnotation沒有該方法。

我嘗試了各種愚蠢的事情,比如將它作為我的自定義注釋並在MKAnnotation上進行擴展。

有關如何從該自定義類中獲取imageUrl的任何想法?

謝謝!

正如我在評論中所說,你需要強制轉換為自定義注釋類,

這是代碼

func mapView(_ map: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

        if let customAnnotation = annotation as? MyAnnotion{
           let imageUrl = customAnnotation.imageUrl()
        }
}

您需要強制轉換為MyAnnotation ,如下所示:

(annotation as! MyAnnotation).imageUrl()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM