在UiTableView中插入行不会更新其余单元格的indexPath?

时间:2015-07-23 12:17:58

标签: objective-c uitableview uitextview

假设我正在加载UITableview,每个单元格中的每个UITextView都作为子视图。我已经将indexPath.row指定为每个文本视图的标记。

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

    static NSString *CellIdentifier = @"userDetails";
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    UITextView *textView=[[UITextView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, 60)];
    NSString * myString = [contentArray1 objectAtIndex:indexPath.row];
    textView.text= myString;

    UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc]
    [tapRecognizer setNumberOfTouchesRequired:1];
    [tapRecognizer setDelegate:self];
    textView.userInteractionEnabled = YES;
    textView.tag = indexPath.row;//assign tags to textview
    [textView addGestureRecognizer:tapRecognizer];
    [cell addSubview:textView];

    return cell;
}

一旦用户点击任何文本视图,就会调用下面的方法。当我点击任何文本视图时,我看到正确的标记值被打印出来。

-(void) action:(id)sender
{
    //NSLog(@"TESTING TAP");
    UITapGestureRecognizer *tapRecognizer = (UITapGestureRecognizer *)sender;

    NSLog (@"%d",[tapRecognizer.view tag]);
}

现在我想在我的tableview中插入行,比如在索引3处。

我所做的很简单,

[contentArray1 insertObject:[NSString stringWithFormat:@"added cell”] atIndex:3];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:3 inSection:0];
[self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];

现在,当我尝试在插入的单元格后点击任何文本视图时,我能够看到旧的标记值。意思是,在将行插入到tableview的index = 3之后,当我点击textview时,我可以看到标记= 2,然后当我点击下一个单元格的textview时我可以看到tag = 2,它应该是3。

我的问题是,一旦我们在tableview中插入任何行/单元格,tableview就不会刷新其他单元格标签/索引?....

我可以通过调用 reloadVisibleCells 方法来修复它。但我正在寻找更好的解决方案。我不想只是为了插入行来刷新整个屏幕。任何解决方案都将非常感谢。

2 个答案:

答案 0 :(得分:1)

尝试这样做:

[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
[self.tableView endUpdates];

答案 1 :(得分:1)

您的问题是插入/删除行不会导致重新加载其他行,这是预期的正确行为。但是,由于没有为其他行调用-tableView:cellForRowAtIndexPath:,因此它们仍配置有旧的(现已过时)标记。

你可以通过多种方式解决它(在我的脑海中):

  • 子类UITableViewCell并将表示的对象本身存储为其属性(而不是对象的索引)
  • 将对象与UITableViewCellobjc_setAssociatedObject()
  • 相关联
  • 使用-[UITableView indexPathForCell:]代替标签来计算单元格的真实索引路径。