Search code examples
iosuitableviewuislideruitouch

slider change affects other table cells


Each of my table cells has a slider and a label to show its value. If I move the slider while keeping all touches inside the cell, the label gets updated as expected. However, if while dragging a slider, the touches cross into another cell, the label for the second cell gets updated while the first cell slider's thumb is moved. How can I restrict the label change to the first cell from which the slider event originated?

-(IBAction)sliderChanged:(id)sender forEvent:(UIEvent*)event
{    
    NSSet *allTouches = [event allTouches];
    UITouch *firstTouch = [[allTouches allObjects] objectAtIndex:0];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:[firstTouch locationInView:self.tableView]];
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];

    if (cell)
    {
        UISlider *slider = (UISlider*)sender;
        UILabel *sliderValueLabel = (UILabel*)[cell viewWithTag:kSliderValueLabelTag];
        sliderValueLabel.text = [NSString stringWithFormat:@"%0.2f", slider.value];
    }
}

Solution

  • Your code looks reasonable to me, although to be consistent, I would get the cell from the "slider" rather than relying on the coordinates of the touch points. It may be that the "allTouches" array doesn't go back as far as you'd like to the original press.

    To do this, you would need to get the superView of the slider, and then use that to get the viewWithTag:.

    Assuming that the slider and label are contained within the same view, you could try something like:

    UIView *cellContentView = slider.superView;
    UILabel *sliderValueLabel = [cellContentView viewWithTag:kSliderValueLabelTag];
    

    If you don't want to rely on view hierarchies, you could also put a tag on the slider that corresponds to the row in your table, and then use that to pull the cell.