gpt4 book ai didi

objective-c - 如何在行中的单元格被删除之前动态更改 UITableViewCell 标签?

转载 作者:行者123 更新时间:2023-11-29 13:22:15 26 4
gpt4 key购买 nike

更新:我解决了这个问题,方法是在 for 循环中循环遍历剩余的单元格,每次递增索引路径的行,直到剩余的数据量为止。

我有一个包含 2 个部分的 UITableView。一节是固定的。另一部分动态变化,用户单击一个按钮并添加一个新行。这些单元格包含三个用户可以编辑的文本框(标记为 1、2 和 3)。此部分中的行是可编辑的,用户可以滑动和删除。所有这些功能目前都运行良好。这是用户界面:

enter image description here

当我尝试更新数据源时无法正常工作。我使用一个包含名为“ReceiptItem”的自定义类对象的数组。当用户编辑单元格中的一个 UITextField 时,我正在更新“ReceiptItem”中的相应属性。我目前正在使用标签来跟踪正在编辑的单元格和文本字段。

我识别正在编辑的单元格和文本字段的代码是:

- (void)textFieldDidEndEditing:(UITextField *)textField{
//find the cell and textfield that just ended editing
int row = textField.superview.tag;
int column = textField.tag;

ReceiptItem *itemToBeUpdated = [[ReceiptItem alloc]init];
itemToBeUpdated = [receiptItemsArray objectAtIndex:row];

//update the receiptItem
switch (column) {
case 1:
//quantity text field
itemToBeUpdated.quantityValue = [textField.text doubleValue];
break;
case 2:
//item text field
if ([textField text].length == 0) {
itemToBeUpdated.itemName = @"Blank";
}
else{
itemToBeUpdated.itemName = [textField text];
}
break;
case 3:
//price text field
itemToBeUpdated.priceValue = [textField.text doubleValue];
break;
}
[receiptItemsArray replaceObjectAtIndex:row withObject:itemToBeUpdated];
}

当一行被删除时,我遇到了问题。我从我的数据源中删除了相应的对象,我的数组计数减一。如果我随后尝试在被删除的单元格下方的单元格中编辑文本字段,我会收到“越界”错误,因为单元格的标记现在大于数组的计数。它发生在这一行(从上面):

itemToBeUpdated = [receiptItemsArray objectAtIndex:row];

我想弄清楚我如何才能 a) 更好地跟踪单元格,b) 在删除一个单元格时重新标记单元格或 c) 其他东西。有答案吗?如果需要,我可以在删除单元格的位置发布代码。

最佳答案

我猜你是在 cellForRowAtIndexPath 的方法中标记 textField if (cell == nil) like,

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

if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]
yourTextField.tag = indexPath.row;
}
}

将标记放在 if block 之外,这样当您删除一行并在重新加载数据时调用您的 textField 将获得如下新标记:

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

if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]

}
yourTextField.tag = indexPath.row;
return cell;
}

关于objective-c - 如何在行中的单元格被删除之前动态更改 UITableViewCell 标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14098786/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com