我有一个包含多个部分的表格视图和自定义表格视图单元格。我试图在我的单元格中放置一个步进器,以及一个指示步进器值的标签。我在视图控制器的单元格中为 UIStepper 添加了一个 IBAction(我认为视图控制器应该处理此事件而不是单元格):
- (IBAction)mealAmountStepperChanged:(id)sender
{
// Get the cell in which the button was pressed
SOMealTableViewCell *cell = (SOMealTableViewCell *)[[sender superview] superview];
// Get the value of the stepper (it has an outlet in my custom cell
int value = cell.mealAmountStepper.value;
// Update the text field of the cell with the new value (also has an outlet in the custom cell)
cell.mealAmountField.text = [NSString stringWithFormat:@"%d",value];
}
问题是这种方法会更新所有部分中的相应字段,而不仅仅是我想要的那个。如何仅更改一个单元格中的文本?
更新:
我在 Meal 类中添加了一个“数量”属性(它为表格视图单元格提供数据)并修改了 mealAmountStepperChanged: 方法:
- (IBAction)mealAmountStepperChanged:(id)sender
{
// Get the cell in which the button was pressed
SOMealTableViewCell *cell = (SOMealTableViewCell *)[[sender superview] superview];
// Get the value of the stepper (it has an outlet in my custom cell
int value = cell.mealAmountStepper.value;
// Get the indexpath of the cell in which the stepper was pressed
NSIndexPath *indexPath = [self.menuTableView indexPathForCell:cell];
SOMealManager *manager = [SOMealManager sharedMealManager];
SOMeal *currentMeal;
switch (indexPath.section)
{
case 0:
currentMeal = manager.startersArray[indexPath.row];
break;
case 1:
currentMeal = manager.soupsArray[indexPath.row];
break;
case 2:
currentMeal = manager.mainDishesArray[indexPath.row];
break;
case 3:
currentMeal = manager.dessertsArray[indexPath.row];
break;
case 4:
currentMeal = manager.drinksArray[indexPath.row];
break;
case 5:
currentMeal = manager.alcoholicDrinksArray[indexPath.row];
break;
default:
break;
}
currentMeal.amount = value;
dispatch_async(dispatch_get_main_queue(), ^
{
[self.menuTableView reloadData];
});
}
现在该操作一次只更新一行,但似乎所有部分的步进器值都保持不变(所以当我更新另一个部分中的单元格时,它不会从 0 开始,而是在值更改为在前面的其他部分)。
最终更新
如果我添加 cellForRowAtIndexPath: 表视图数据源方法可以解决前面的问题:
cell.mealAmountStepper.value = currentMeal.amount;
它将步进器的值设置为 Meal 对象的 amount 属性,以便正确更改。