【问题标题】:Changing annontation image on iOS depending on object type根据对象类型在 iOS 上更改注释图像
【发布时间】:2018-04-30 09:46:48
【问题描述】:

我正在尝试根据注释包含的值更改MKMarkerAnnontationView 的图像。所有注释都使用此代码获得相同的图像,我需要根据用户选择的值以某种方式设置图像。因此,当用户按下另一种类型的停车时,使用的是同一个对象,但使用了另一种类型。

我试图强制重新加载注释,但我没有让它工作。有什么可以帮我的吗?

if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKMarkerAnnotationView {
            dequeuedView.annotation = annotation
            view = dequeuedView
        } else {

            view = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: identifier)
            view.canShowCallout = true
            view.glyphTintColor = UIColor.white
            view.calloutOffset = CGPoint(x: -5, y: 5)

            if annotation.type == .bus {
                view.glyphImage = UIImage(named: "bus")
            } else if annotation.type == .disabled {
                view.glyphImage = UIImage(named: "disabled")
            } else if annotation.type == .MC {
                view.glyphImage = UIImage(named: "mc")
            }
        }
        return view
    }
    return nil
}

【问题讨论】:

  • 你可以在 if else 块之前添加 debugPrint(annotation.type) 并确保类型不同吗?

标签: ios swift maps mapkit mkannotation


【解决方案1】:

我遇到了这样的问题,我解决它的唯一方法是从 MKMapView 中删除所有数据点,然后读取它们,唯一的区别是 func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView] )我正在检查 MKAnnotationView 的标题。 为了实现这一点,我创建了一个扩展 MKAnnotationView 的对象类,女巫也有一个标题变量,所以我的注释列表就是类对象。 当用户更改 MKAnnotation 的图像时,您会更改选项中的标题变量,然后您首先要做

self.sceneView.removeAnnotations(annotations)

在你重新添加注释点之后。将被调用的委托函数将是这样的

func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) {
    for view in views{
        if((view.annotation is MKUserLocation) == false){
            // Resize image
            let dt:DataPoint = view.annotation as! DataPoint //Data point is my class
            var pinImage:UIImage!
            if(dt.title = "example"){
                pinImage = exampleImage
                size = CGSize(width: 60, height: 60) //whetever size
            }else{
                pinImage = anotherImage
            }
            UIGraphicsBeginImageContext(size)
            pinImage?.draw(in: CGRect(x:0, y:0, width: size.width, height: size.height))
            let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            view.image = resizedImage
        }
    }
}

【讨论】:

    猜你喜欢
    • 2011-08-07
    • 2017-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-06
    • 2011-07-06
    • 2016-07-31
    相关资源
    最近更新 更多