我使用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图例可以有一个委托,在鼠标向下、鼠标向上和/或被选中(鼠标向下和鼠标向上在同一项上)事件时调用。有关可用方法的详细信息,请参阅CPTLegendDelegate协议。除非你需要一些委托没有涵盖的特定行为,否则你不需要担心响应器链。
如果您深入研究Core Plot的源代码,您可以遵循CPTLegend的继承链一直到CPTLayer:
https://github.com/core-plot/core-plot/blob/master/framework/Source/CPTLegend.hhttps://github.com/core-plot/core-plot/blob/master/framework/Source/CPTBorderedLayer.hhttps://github.com/core-plot/core-plot/blob/master/framework/Source/CPTAnnotationHostLayer.hhttps://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:(非空CPTNativeEvent *)事件atPoint:(CGPoint)interactionPoint;
-(BOOL)pointingDeviceUpEvent:(非空CPTNativeEvent *)事件atPoint:(CGPoint)interactionPoint;
我认为你可能做的是子类化CPTLegend和覆盖一个或两个方法取决于你需要检测点击