首页 > 解决方案 > 更改现有 MKAnnotation 上的自定义图像

问题描述

我有一个带有地图视图的简单屏幕,我以典型的方式在其上添加了几个自定义注释。当某些事件发生时,我现在需要返回并更改图像;本质上只是更改图像以显示一个小标志,指示特定注释具有更多可用数据,用户可以选择点击。

认为我必须做的是删除有问题的注释,将其所有数据复制到具有新图像的新数据中,然后重新添加它,从而使用 viewFor 注释并检查注释基础数据的更新性质。

好像有点过分了。

有没有办法简单地说:

for var ann in self.eventMap.annotations {
    if let ann2 = ann as? CustomPointAnnotation { // custom type with properties
        if "myCustomIdValueHere" == ann2.myCustomId {
            // found it.
            print( "Found the one I'm looking for" )

            // then change its image from "[existingImageName]" to "[existingImageName]Attention"
        }
    }
}

标签: iosswiftxcodemkmapview

解决方案


您可以使用 view(for: ) 方法获取特定的 MKAnnotationView。试试下面的代码:

for var ann in self.eventMap.annotations {
    if let ann2 = ann as? CustomPointAnnotation { // custom type with properties
        if "myCustomIdValueHere" == ann2.myCustomId {
            // found it.
            print( "Found the one I'm looking for" )

            // then change its image from "[existingImageName]" to "[existingImageName]Attention"
            let annotationView = self. eventMap.view(for: ann2)
            annotationView?.image = UIImage(named: "[existingImageName]Attention")            }
    }
}

推荐阅读