tintColor - 随机颜色,为什么?

时间:2017-05-21 10:55:52

标签: ios swift dictionary mapkit tintcolor

我的课程中有tintColor函数:

func pinColor() -> UIColor  {
    switch status.text! {
    case "online":
        return UIColor(red: 46/255, green: 204/255, blue: 113/255, alpha: 1.0)
    default:
        return UIColor.red
    }
}

我也有这个扩展名:

extension ViewController: MKMapViewDelegate {

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if let annotation = annotation as? Marker {
        let identifier = "pin"
        var view: MKPinAnnotationView
        if let dequeuedView = map.dequeueReusableAnnotationView(withIdentifier: identifier)
            as? MKPinAnnotationView {
            dequeuedView.annotation = annotation
            view = dequeuedView
        } else {
            view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
            view.canShowCallout = true
            view.calloutOffset = CGPoint(x: -5, y: 5)
            view.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) as UIView
            view.pinTintColor = annotation.pinColor()
        }
        return view
    }
    return nil
 }
}

我每隔10秒用mapView的数组加载我的数据,然后像这样显示:

    func mapView() {
    map.layoutMargins = UIEdgeInsets(top: 30, left: 30, bottom: 30, right: 30)
    map.showAnnotations(markersArrayFiltered!, animated: true)
}

错误: - 每次加载新数据时,我的引脚颜色都不同,但我的数据不会改变。

Watch example video of error

我做错了什么?

1 个答案:

答案 0 :(得分:2)

您正在使用dequeueReusableAnnotationView,它返回由其标识符定位的可重复使用的注释视图。

但是,您只是在首次初始化MKPinAnnotationView时设置了引脚颜色。您必须在两种情况下进行设置。对于基于数据的所有内容,这不仅适用于引脚颜色。

extension ViewController: MKMapViewDelegate {

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if let annotation = annotation as? Marker {
        let identifier = "pin"
        var view: MKPinAnnotationView
        if let dequeuedView = map.dequeueReusableAnnotationView(withIdentifier: identifier)
            as? MKPinAnnotationView {
            dequeuedView.annotation = annotation
            view = dequeuedView
        } else {
            view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)

        }
         view.canShowCallout = true
         view.calloutOffset = CGPoint(x: -5, y: 5)
         view.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) as UIView
         view.pinTintColor = annotation.pinColor()
        return view
    }
    return nil
 }
}