删除多个单元格后,uitableview会添加一些行

时间:2013-05-07 12:53:06

标签: ios uitableview

我正在使用“轻扫删除”,如果我想删除序列中的多个单元格,则uitableview中的某些单元格会加倍,或者会出现一些已删除的单元格。因为我不能发布任何图像,我将描述表格的行为:

  1. 删除单元格前的表格:User1,User2,User3,User4,User5,添加新用户。
  2. 删除User1和User5后的表:User2,User3,User4,添加新用户,添加新用户(但不可选)。
  3. 删除User3后的表:User4,User2,添加新用户, User5 (可选),添加新用户(不可选)。
  4. 我删除单元格的方法如下:

    - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
       if (editingStyle == UITableViewCellEditingStyleDelete) {
          [self.usersTable beginUpdates];
          UITableViewCell *cell = (UITableViewCell *)[self.usersTable cellForRowAtIndexPath:indexPath];
          NSString *userNameToDelete = cell.textLabel.text;
          // Data source
          [self.appDict removeObjectForKey:userNameToDelete];
          self.arrayOfUserNames = [[NSMutableArray alloc] initWithArray:[self.appDict allKeys]];
          [self.appDict writeToFile:self.pathOfAppFile atomically:YES];
          // Deleting cell
          [self.usersTable deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]  withRowAnimation:UITableViewRowAnimationFade];
          [self.usersTable endUpdates];
       }
    }
    

    支持编辑的方法:

    - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == [self.arrayOfUserNames count]) {
       return NO;
    }
    else {
       return YES;
    }
    

    部分中的行数:

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
       return [self.arrayOfUserNames count] + 1;
    }
    

    我已经尝试过[self.usersTable reload],但一切都保持不变。我也尝试在numberOfRowsInSection中更改表的大小:但这也没有帮助。有什么想法我做错了什么?

1 个答案:

答案 0 :(得分:0)

你没有实施

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //delete your user record
    }    
}

如果不是Tableview将删除单元格,但基础数据将不会被修改,并导致这种奇怪的行为。

修改

尝试使用:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
   if (editingStyle == UITableViewCellEditingStyleDelete) {

      NSString *userNameToDelete = [[self arrayOfUserNames] objectAtIndex:indexPath.row];
      // Data source
      [self.appDict removeObjectForKey:userNameToDelete];
      self.arrayOfUserNames = [[NSMutableArray alloc] initWithArray:[self.appDict allKeys]];
      [self.appDict writeToFile:self.pathOfAppFile atomically:YES];

      [tableView reloadData];


   }
}

给出一个简短的解释:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
调用

,从tableview中删除了tablecell,因此你不必处理这个问题。如果你这样做,你将删除下一个单元格。