class 上符合 MKAnnotation 协议的自定义方法
Custom method on class that conforms to MKAnnotation protocol
我有一个 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
}
}
当我将注释加载到地图中时,我将它们加载为 MyAnnotion
s。
mapView viewFor:
函数传递了一个 MKAnnotation
注释,但当我检查它时它实际上是一个 MyAnnotation
。
问题是,如果我尝试访问 imageUrl() 方法,它会告诉我 MKAnnotation 没有该方法。
我已经尝试过各种愚蠢的事情,比如将其转换为我的自定义注释并在 MKAnnotation 上进行扩展。
关于如何从该自定义 class 获取 imageUrl 的任何想法?
谢谢!
您需要强制转换为 MyAnnotation
,如下所示:
(annotation as! MyAnnotation).imageUrl()
您需要转换为您的自定义注释 class,正如我在评论中所说,
这是代码
func mapView(_ map: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if let customAnnotation = annotation as? MyAnnotion{
let imageUrl = customAnnotation.imageUrl()
}
}
我有一个 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
}
}
当我将注释加载到地图中时,我将它们加载为 MyAnnotion
s。
mapView viewFor:
函数传递了一个 MKAnnotation
注释,但当我检查它时它实际上是一个 MyAnnotation
。
问题是,如果我尝试访问 imageUrl() 方法,它会告诉我 MKAnnotation 没有该方法。
我已经尝试过各种愚蠢的事情,比如将其转换为我的自定义注释并在 MKAnnotation 上进行扩展。
关于如何从该自定义 class 获取 imageUrl 的任何想法?
谢谢!
您需要强制转换为 MyAnnotation
,如下所示:
(annotation as! MyAnnotation).imageUrl()
您需要转换为您的自定义注释 class,正如我在评论中所说,
这是代码
func mapView(_ map: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if let customAnnotation = annotation as? MyAnnotion{
let imageUrl = customAnnotation.imageUrl()
}
}