子类化MKGeodesicPolyline

时间:2017-09-01 09:40:20

标签: ios swift mapkit

我试图将MKPolylineMKGeodesicPolyline子类化以存储他们自己的颜色(通过让子类实例返回自己的MKPolylineRenderer)。它适用于MKPolyline,但我的MKGeodesicPolyline子类的实例不是子类 - 只是MKGeodesicPolyline s。有谁能解释为什么?这是我的代码......

protocol MapLineProtocol: MKOverlay {
    var width: CGFloat { get set }
    var colour: UIColor { get set }
}
extension MapLineProtocol {
    var renderer: MKPolylineRenderer {
        let polylineRenderer = MKPolylineRenderer(overlay: self)
        polylineRenderer.strokeColor = self.colour
        polylineRenderer.lineWidth = self.width
        return polylineRenderer
    }
}
class MapLine: MKPolyline, MapLineProtocol {
    var width: CGFloat = 3
    var colour: UIColor = .blue
    convenience init(start: CLLocationCoordinate2D, end: CLLocationCoordinate2D) {
        let line = [start, end]
        self.init(coordinates: line, count: line.count)
    }
}
class MapGeodesic: MKGeodesicPolyline, MapLineProtocol {
    var width: CGFloat = 3
    var colour: UIColor = .red
    convenience init(start: CLLocationCoordinate2D, end: CLLocationCoordinate2D) {
        let line = [start, end]
        self.init(coordinates: line, count: line.count)
    }
}

let mapLine = MapLine(start: loc.coordinate, end: end)
print("Mapline subclass: \(mapLine)") // <Appname.MapLine: xxx>
self.mapView.add(mapLine)
let geoLine = MapGeodesic(start: loc.coordinate, end: end)
print("Geodesic subclass: \(geoLine)") // <MKGeodesicPolyline: xxx> !!!
self.mapView.add(geoLine)

访问.colour上的mapLine属性很好(并且渲染器可以正常工作),但访问geoLine上的.colour会导致运行时异常(当然,如果绕过颜色,渲染器也不起作用)。有人可以解释一下吗?

1 个答案:

答案 0 :(得分:0)

我无法捕捉到确切的问题..但根据我的分析.. MKGeodesicPolyline继承自MKPolyline。因此,当你初始化MKGP时也会初始化父MKP,因为使用Convenience Init会让我觉得有些混乱......