删除表的单元格时出现的问题



在我的表(UITableView)中,我使用UITextField而不是UILabel的单元格,通过"addSubview"添加到单元格中。我需要这个,因为我想让单元格直接可编辑。作为细胞样式,我使用UITableViewCellStyleDefault。-一切都很好:我可以随时添加和编辑单元格。

然而,删除会产生一个问题:当我"删除"一个单元格并在表中创建一个reloadData时,单元格仍然显示其旧内容和新内容。它下面的所有单元格也是一样的。当我关闭我的应用程序并再次启动它时,表格显示正确。

下面是我用来删除单元格 的代码
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle 
                                            forRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger row = [indexPath row];
NSUInteger count = [datas count];
if (row <= count) {
    NSString* data = [datas objectAtIndex: [indexPath row]];
    [self deleteDatas:data];
}
[self.locationTable reloadData];

}

deleteDatas中,我只是从文件中删除相应的数据,该文件正常工作,作为新加载应用程序的"证明"。

这里

 -(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];
    UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
    longPressGesture.minimumPressDuration = 2.0;
    [cell addGestureRecognizer:longPressGesture];
}
// Configure the cell.
// table cell with uitextfield instead of lable.
UITextField* textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, 185, 30)];
textField.enabled = NO;
[cell.contentView addSubview:textField];
NSUInteger count = [datas count];
NSUInteger row = [indexPath row];
// last cell is empty to edit it
if (row+1 < count) {
    textField.text = [datas objectAtIndex:[indexPath row]];
    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
}
return cell;

}

任何想法?-谢谢

任何想法,为什么我的单元格显示了两次内容(一次是原始单元格,一次是下面单元格的内容?)-我认为s.s th。是错误的重新加载单元格。-是否有可能使文本字段的问题?-我怎么知道?

你应该这样写你的commitEditingStyle:方法:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
  if (editingStyle == UITableViewCellEditingStyleDelete) {
    if (indexPath.row <= [data count]) {
      // Update the model by deleting the actual data
      NSString* data = [datas objectAtIndex:indexPath.row];
      [self deleteDatas:data];
      // Delete the row from the table
      [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationBottom];
    }
  }
}

其他事情要检查,是你的方法tableView:numberOfRowsInSection:返回正确的数据,如果它没有,那么你会得到断言失败时,表试图删除行,逻辑不加起来

我认为你也应该从你的可变数组中删除元素,在commitEditingStyle…

NSString* data = [datas objectAtIndex: [indexPath row]];
[self deleteDatas:data];
[datas removeObjetAtIndex: [indexPath row]];

否则在你的下一个reloadData字符串仍然在内存中,并显示在cellForRow…

最新更新