【问题标题】:tintColor - random color, why?tintColor - 随机颜色,为什么?
【发布时间】:2017-10-21 02:47:39
【问题描述】:

我的班级中有一个 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

我做错了什么?

【问题讨论】:

    标签: ios swift dictionary mapkit tintcolor


    【解决方案1】:

    您正在使用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
     }
    }
    

    【讨论】:

    • 谢谢!现在一切正常。现在我对 mapKit 有了更多了解 =)
    猜你喜欢
    • 2017-06-08
    • 2016-08-29
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    • 2012-08-31
    • 2014-09-08
    • 2012-10-13
    • 2017-08-09
    相关资源
    最近更新 更多