Search code examples
iosobjective-ccore-plot

How to toggle graph visibility with CPTLegend as button


I would like to allow toggling on/off individual plots on my CorePlot based graph. The most reasonable way to do this I think would be to allow each Legend item to act as a button. I am not sure how to do this however as a CPTLegend is a CALayer not a UIView and also because the CPTLegend represents all of the legend items, and I would need toggle actions associated with each individual legend item managed internally by it.


Solution

  • You can use a legend delegate to monitor for touches on the legend and respond accordingly. See the "Math Function Plot" and "Simple Pie Chart" in the Plot Gallery example app for sample code.

    For example, here's the delegate function from the function plot example that toggles visibility of the selected plot:

    -(void)legend:(nonnull CPTLegend *__unused)legend 
        legendEntryForPlot:(nonnull CPTPlot *)plot
        wasSelectedAtIndex:(NSUInteger __unused)idx
    {
        plot.hidden = !plot.hidden;
    }