我试图将MKPolyline
和MKGeodesicPolyline
子类化以存储他们自己的颜色(通过让子类实例返回自己的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
会导致运行时异常(当然,如果绕过颜色,渲染器也不起作用)。有人可以解释一下吗?
答案 0 :(得分:0)
我无法捕捉到确切的问题..但根据我的分析.. MKGeodesicPolyline继承自MKPolyline。因此,当你初始化MKGP时也会初始化父MKP,因为使用Convenience Init会让我觉得有些混乱......