简体   繁体   中英

Custom method on class that conforms to MKAnnotation protocol

I have a class:

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
}
}

When I load my annotations into the map, I load them as MyAnnotion s.

The mapView viewFor: function passes an MKAnnotation annotation but when I check it's actually a MyAnnotation .

Trouble is, if I try to access the imageUrl() method it tells me that MKAnnotation doesn't have that method.

I've tried all sorts of silly things like casting it as my custom annotation and making an extension on MKAnnotation.

Any ideas how to grab the imageUrl from that custom class?

Thanks!

You need cast to your custom annotation class, as I said in my comments,

this is the code

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

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

您需要强制转换为MyAnnotation ,如下所示:

(annotation as! MyAnnotation).imageUrl()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM