1

当点击图例中的相关色板颜色时,我试图隐藏/显示图,这是我的代码:

-(void)configureLegend
{
    // 1 - Create styles
    CPTMutableTextStyle *axisTitleStyle = [CPTMutableTextStyle textStyle];
    axisTitleStyle.color = [CPTColor whiteColor];
    axisTitleStyle.fontName = @"Helvetica-Bold";
    axisTitleStyle.fontSize = 12.0f;
    CPTMutableLineStyle *axisLineStyle = [CPTMutableLineStyle lineStyle];
    axisLineStyle.lineWidth = 2.0f;
    axisLineStyle.lineColor = [CPTColor whiteColor];
    CPTMutableTextStyle *axisTextStyle = [[CPTMutableTextStyle alloc] init];
    axisTextStyle.color = [CPTColor whiteColor];
    axisTextStyle.fontName = @"Helvetica-Bold";
    axisTextStyle.fontSize = 11.0f;

    // Add legend
    CPTGraph *graph = self.hostView.hostedGraph;
    graph.legend                 = [CPTLegend legendWithGraph:graph];
    graph.legend.delegate = self;
    graph.legend.numberOfRows    = 2;
    graph.legend.textStyle       = axisTitleStyle;
    graph.legend.fill            = [CPTFill fillWithColor:[CPTColor darkGrayColor]];
    graph.legend.borderLineStyle = axisLineStyle;
    graph.legend.cornerRadius    = 5.0;
    graph.legend.swatchSize      = CGSizeMake(5.0, 5.0);
    graph.legendAnchor           = CPTRectAnchorBottom;
    graph.legendDisplacement     = CGPointMake(20.0, 35.0);
}


-(BOOL)legend:(CPTLegend *)legend shouldDrawSwatchAtIndex:(NSUInteger)idx forPlot:(CPTPlot *)plot inRect:(CGRect)rect inContext:(CGContextRef)context
{
    NSLog(@"\n Swatch Index = %d",idx);
    CPTGraph *graph = self.hostView.hostedGraph;
    if (CGRectEqualToRect(plot.legendRect, CGRectZero)) {
        plot.legendRect = CGRectUnion(graph.legend.frame, rect);
    }
    return !plot.hidden;
}

-(BOOL)plotSpace:(CPTPlotSpace *)space shouldHandlePointingDeviceDownEvent:(UIEvent *)event atPoint:(CGPoint)point
{
    CPTGraph *graph = self.hostView.hostedGraph;
    if (CGRectContainsPoint(graph.legend.frame, point)) {

        CGPoint pointInLegend = CGPointMake(point.x - graph.legend.frame.origin.x, point.y - graph.legend.frame.origin.y);

        [graph.allPlots enumerateObjectsUsingBlock:^(CPTPlot *plot, NSUInteger idx, BOOL *stop) {
            if (CGRectContainsPoint(plot.legendRect, pointInLegend))
            {
                NSLog(@"\n Index Value = %d",idx);
                //here you can do whatever you need
                plot.hidden = !plot.hidden;
                [self configureLegend];
                *stop = YES;
            }
        }];
    }
    return YES;
}

但我在这里面临的问题是我的图表包含 7 个图,然后我在图例中表示为 2 行。当我点击第一行中的第一个图例项(红色)时,隐藏了红色图。当我点击第二行中的第一项(黄色)时,黄色图被隐藏。这工作正常。如果我点击第一行中的 3 项(蓝色),则红色图再次隐藏而不是蓝色图。第二行黄色颜色图发生的相同情况是隐藏而不是橙色。

任何人都建议我在哪里做错了,并采用了获得正确结果的方法。

4

1 回答 1

1

当用户触摸图例条目时,使用图例委托接收通知。这些方法是在 1.3 版之后添加的:

-(void)legend:(CPTLegend *)legend legendEntryForPlot:(CPTPlot *)plot wasSelectedAtIndex:(NSUInteger)idx;
-(void)legend:(CPTLegend *)legend legendEntryForPlot:(CPTPlot *)plot wasSelectedAtIndex:(NSUInteger)idx withEvent:(CPTNativeEvent *)event;
于 2013-09-18T23:56:33.773 回答