Search code examples
iosuitableviewuistepper

iOS: UIStepper within UITableView Cells


I never really had the need to use UIStepper, so I thought I would try it.

And I tried it within table cells. The following is my code:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    UIStepper *stepper = [[UIStepper alloc] initWithFrame:(CGRect){{40, 40}, 20, 20}];
    [stepper addTarget:self action:@selector(stepperTapped:) forControlEvents:UIControlEventValueChanged];
    stepper.tag = indexPath.row;
    stepper.stepValue = 1;
    stepper.continuous = YES;
    stepper.minimumValue = 0;
    stepper.maximumValue = 10;
    [cell.contentView addSubview:stepper];

    return cell;
}

Action method:

- (void)stepperTapped:(UIStepper*)stepper
{
    NSLog(@"sender tag: %li", (long)stepper.tag);

    UITableViewCell *currentCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:stepper.tag inSection:0]];
    NSNumber *stepperValue = [NSNumber numberWithDouble:stepper.value];
    currentCell.textLabel.text = [NSString stringWithFormat:@"%f", stepper.value];
    [self.tableView reloadData];
}

Am just testing it with 4 cells and 1 section.

It runs, but the stepper only increments once (0 -> 1 or 1 -> 0), it won't go up until 10, which is the maximum number I set.

I tested the same code not within table cell and it works fine. From 0 to 10, and from 10 to 0, each step.

This little experiment has cost me 2 hours trying to find a solution.

Can anyone spot the problem here?


Solution

  • This works fine in Objective C - Xcode 6.4.

    - (IBAction)itemsChange:(UIStepper *)sender{    
        double value = [sender value];
        CGPoint cursorPosition = [sender convertPoint:CGPointZero toView:self.tableView];
        NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:cursorPosition];
        UITableViewCell *currentCell = [self.tableView cellForRowAtIndexPath:indexPath];
        [currentCell.label setText:[NSString stringWithFormat:@"%d", (int)value]];
    }