Core Plot 中的可点击图例

Clickable legend at Core Plot

我使用 Core Plot 文件来创建我的图表。 但是 CorePlot 不包含事件 "click on legend item".

如何检测用户对图例项的点击?

class ViewController: NSViewController, CPTPlotDataSource, CPTPieChartDataSource {

@IBOutlet weak var graphView: CPTGraphHostingView!

override func viewDidLoad() {
    super.viewDidLoad()

    let graph = CPTXYGraph(frame: CGRect.zero)        
    var axes = graph.axisSet as! CPTXYAxisSet
    var lineStyle = CPTMutableLineStyle()
    lineStyle.lineWidth = 0
    axes.xAxis?.axisLineStyle = lineStyle
    axes.yAxis?.axisLineStyle = lineStyle


    var pie = CPTPieChart()
    pie.pieRadius = 100
    pie.dataSource = self
    pie.centerAnchor = CGPoint(x: 0.18, y: 0.75)
    graph.add(pie)        

    var theLegend=CPTLegend(graph: graph)
    var legendFill=CPTFill(color: CPTColor.gray())
    theLegend.fill = legendFill
    var legendLineStyle = CPTMutableLineStyle()
    legendLineStyle.lineColor = CPTColor.white()
    theLegend.borderLineStyle = legendLineStyle
    theLegend.cornerRadius = 2.0
    theLegend.frame = CGRect(x: 0, y: 0, width: 0.1, height: 50)
    theLegend.numberOfColumns = 1

    graph.legend = theLegend
    graph.legendDisplacement = CGPoint(x: 0.5, y: 300)

    self.graphView.hostedGraph = graph
}

如果深挖Core Plot的源码,可以顺着CPTLegend的继承链一直追到CPTLayer:

https://github.com/core-plot/core-plot/blob/master/framework/Source/CPTLegend.h https://github.com/core-plot/core-plot/blob/master/framework/Source/CPTBorderedLayer.h https://github.com/core-plot/core-plot/blob/master/framework/Source/CPTAnnotationHostLayer.h https://github.com/core-plot/core-plot/blob/master/framework/Source/CPTLayer.h

如果你检查CPTLayer的头文件,它符合CPTResponder,如果你去CPTResponder的源码:

https://github.com/core-plot/core-plot/blob/master/framework/Source/CPTResponder.h

您会注意到其中有两种相关方法:

-(BOOL)pointingDeviceDownEvent:(nonnull CPTNativeEvent *)event atPoint:(CGPoint)interactionPoint;

-(BOOL)pointingDeviceUpEvent:(nonnull CPTNativeEvent *)event atPoint:(CGPoint)interactionPoint;

我认为您可能做的是继承 CPTLegend 并根据检测点击的需要重写一个或两个方法。

Core Plot 图例可以有一个委托,在鼠标按下、鼠标抬起、and/or 选中(在同一项目上鼠标按下后鼠标抬起)事件被调用。有关可用方法的详细信息,请参阅 CPTLegendDelegate protocol。除非您需要委托未涵盖的某些特定行为,否则您无需担心响应者链。