![](/img/trans.png)
[英]how to create a custom class that conforms to <MKAnnotation> protocol
[英]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.