简体   繁体   English

类的自定义方法符合MKAnnotation协议

[英]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. 当我将注释加载到地图中时,我将它们加载为MyAnnotion

The mapView viewFor: function passes an MKAnnotation annotation but when I check it's actually a MyAnnotation . mapView viewFor:函数传递一个MKAnnotation注释,但当我检查它实际上是一个MyAnnotation

Trouble is, if I try to access the imageUrl() method it tells me that MKAnnotation doesn't have that method. 麻烦的是,如果我尝试访问imageUrl()方法,它告诉我MKAnnotation没有该方法。

I've tried all sorts of silly things like casting it as my custom annotation and making an extension on MKAnnotation. 我尝试了各种愚蠢的事情,比如将它作为我的自定义注释并在MKAnnotation上进行扩展。

Any ideas how to grab the imageUrl from that custom class? 有关如何从该自定义类中获取imageUrl的任何想法?

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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