我正在开发一个请求多个方向 (MKDirectionsRequest) 并在 mapView 中绘制路线的应用程序,一切正常。
但我面临一个问题:我想用不同的颜色绘制每条路线。
第一个想法很简单:使用标题/副标题来“标记”不同的 MKPolyline,这样我就可以在委托(delegate)函数中设置我想要的颜色:
mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer
但我不喜欢这个解决方案,因为它“丑陋”,而且我将不得不在必须传递不同参数(交通..)的那一天解析一个字符串
第二个简单的解决方案是将 MKPolyline 子类化,很简单.. 因为 MKPolyline 没有指定的初始值设定项,所以这是不可能的(是吗?)
[编辑]:我想创建一个 MKPolyline 的子类来复制“在其上”由 MKDirectionsRequest.routes 返回的已经创建的 MKPolyline 但我不知道如何覆盖只读参数(Apple 说我们应该在子类中覆盖它们并添加 setter,但我在 setter 中有一个无限循环女巫是..正常)
如果使用的是 objC,那么在运行时“注入(inject)”代码并添加我的参数会很简单,但我使用的是 swift。
谁能帮忙解决这个问题,谢谢。
最佳答案
不需要自定义渲染器的更简单的方法:
import UIKit
import MapKit
class CustomPolyline : MKPolyline {
var color: UIColor?
}
class ViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
// setup mapView
mapView.delegate = self
// set map view region
let location : CLLocationCoordinate2D = CLLocationCoordinate2DMake(51.4987, 0.007);
let viewRegion = MKCoordinateRegionMakeWithDistance(location, 400, 400)
mapView.setRegion(viewRegion, animated:true )
// add red line
let coords1 = [CLLocationCoordinate2D(latitude: 51.499526, longitude: 0.004785),CLLocationCoordinate2D(latitude: 51.500007, longitude: 0.005493)]
let polyline1 = CustomPolyline(coordinates: coords1, count: coords1.count)
polyline1.color = UIColor.red
mapView.add(polyline1)
// add blue line
let coords2 = [CLLocationCoordinate2D(latitude: 51.498103, longitude: 0.007574), CLLocationCoordinate2D(latitude: 51.498190, longitude: 0.009677)]
let polyline2 = CustomPolyline(coordinates: coords2, count: coords2.count)
polyline2.color = UIColor.blue
mapView.add(polyline2)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if overlay is CustomPolyline {
let polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.strokeColor = (overlay as! CustomPolyline).color
polylineRenderer.lineWidth = 4
return polylineRenderer
}
return MKOverlayRenderer()
}
}
关于ios - Swift:子类 MKPolyline,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40908573/