1

我从来没有真正需要使用UIStepper,所以我想我会尝试一下。

我在表格单元格中尝试过。以下是我的代码:

- (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;
}

动作方法:

- (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];
}

我只是用 4 个单元和 1 个部分对其进行测试。

它运行,但步进器只增加一次(0 -> 1 或 1 -> 0),直到 10 才会上升,这是我设置的最大数字。

我测试了不在表格单元格中的相同代码,它工作正常。从 0 到 10,从 10 到 0,每一步。

这个小实验花了我 2 个小时试图找到解决方案。

任何人都可以在这里发现问题吗?

4

2 回答 2

4

这在 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]];
}
于 2015-09-09T21:33:06.907 回答
0

这样做,

UIStepper仅当单元格为零时创建。

- (UITableViewCell *)tableView:(UITableView *)tableView1 cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell Identifier";

    UITableViewCell *cell = [tableView1 dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

        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;
}
于 2014-02-12T13:12:27.493 回答