Tap gesture on bar labels


#1

Hi,

I have an horizontal bar chart in which the datapoint labels are placed above the bar, outside the datapoint area.

When I tap on a bar, a certain action is executed. I’d like to have the same effect by tapping on the label, but something is not working.

Since I already implemented the delegate method sChart:alterDataPointLabel:forDataPoint:inSeries: to move the labels outside the bars, I added these lines:

UITapGestureRecognizer *tapLabel = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapLabelAction:)];
tapLabel.numberOfTapsRequired = 1;
[label addGestureRecognizer:tapLabel];

but the tapLabelAction: method is never called. I even tried to set label.userInteractionEnabled = YES; but nothing changes.

Any suggestion?

Thanks,
Alberto


#2

Hi Punkers,

The canvas overlay is the component responsible for detecting all the gestures that the chart can respond to out of the box. Because the datapoint labels are positioned on a view which is positioned behind this overlay, the overlay ends up ‘swallowing’ the gesture.

The easiest way to get around this is to move the labels up from their default view to the overlay itself. It’s not particularly elegant, but is probably the easiest way to get what you want:

- (void)sChart:(ShinobiChart *)chart alterDataPointLabel:(SChartDataPointLabel *)label forDataPoint:(SChartDataPoint *)dataPoint inSeries:(SChartSeries *)series {
    label.userInteractionEnabled = YES;
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped)];
    recognizer.numberOfTapsRequired = 1;
    [label addGestureRecognizer:recognizer];
    
    // Move label from glview to canvas overlay
    UIView *glView = (UIView *)chart.canvas.glView;
    label.center = [chart.canvas.overlay convertPoint:label.center fromView:glView];
    [chart.canvas.overlay addSubview:label];
}

- (void)tapped {
    NSLog(@"Data point label tapped!");
}

I hope that works for you!

Sam


#3

Thank you Sam, that worked perfectly!

Alberto