You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift MapKit多折线颜色异常:所有折线显示最后设置的颜色

问题原因及解决方案

问题出在坐标数组的作用域上:你在showAllRoutes函数中将coordinates数组定义在了循环外部,每次循环仅向数组追加当前路线的坐标,没有清空历史数据。这导致后续创建的MKPolyline会包含之前所有路线的坐标点,最后一条红色折线会完全覆盖前面的蓝色折线,视觉上看起来所有折线都是红色。

修复代码

将coordinates数组的声明移到内部循环中,确保每次循环都使用全新的空数组存储当前路线的坐标:

func showAllRoutes(map: MKMapView, route: Routes) {
    if dm.show_all_routes {
        for x in route.routes.indices {
            // 每次循环初始化新的坐标数组
            var coordinates: [CLLocationCoordinate2D] = []
            for y in route.routes[x].route_numbers {
                coordinates.append(CLLocationCoordinate2D(latitude: dm.alle_staende.locations[y].latitude, longitude:dm.alle_staende.locations[y].longitude))
            }
            
            let overlay = MKPolyline(coordinates: coordinates, count: coordinates.count)
            overlay.subtitle = "Route"
            overlay.title = "\(x)"
            
            map.addOverlay(overlay)
        }
    }
}

你的渲染器代码逻辑是正确的,修复坐标数组问题后,每个折线会根据自身的title显示对应颜色:title为"2"的折线显示红色,其余显示蓝色。

内容的提问来源于stack exchange,提问作者Hasenburg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 05:45:15