swift - 如何在移动行后再次调用 cellForRowAtIndexPath?

标签 swift uitableview

移动行后,我更改了与单元格关联的业务的 line 和 Pin 编号。如果再次调用 cellForRowAtIndexpath,那么一切都会正常进行。

enter image description here

这是我的代码

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    NSMutableArray *  mutableBusinessBookmarked= self.businessesBookmarked.mutableCopy;
    Business *bizToMove = mutableBusinessBookmarked[sourceIndexPath.row];
    [mutableBusinessBookmarked removeObjectAtIndex:sourceIndexPath.row];
    [mutableBusinessBookmarked insertObject:bizToMove atIndex:destinationIndexPath.row];
    self.businessesBookmarked=mutableBusinessBookmarked;
    [self rearrangePin];
    [tableView moveRowAtIndexPath:sourceIndexPath toIndexPath:destinationIndexPath];
    [self.table reloadData];
}
  1. 我不确定自己做得对不对。我更新了数据模型并调用了 moveRowAtIndexPath
  2. [tableView moveRowAtIndexPath... 似乎没有做任何事情。无论我是否调用,行都会移动。
  3. 我不认为调用 self.table reloadData 是明智的。但是,我想更新左边的数字。尽管调用了 self.table reloadData,但仍未调用 cellForRowAtindexpath

最佳答案

我建议将您的单元格配置逻辑移到一个单独的方法中。然后在moveRowAtIndexPath中,可以直接调用这个方法来更新可见单元格。例如:

- (void)configureCell:(UITableViewCell *)cell
{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    // Get data for index path and use it to update cell's configuration.
}

- (void)reconfigureVisibleCells
{
    for (UITableViewCell *cell in self.tableView.visibleCells) {
        [self configureCell:cell];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCellIdentifier"];
    [self configureCell:cell];
    return cell;
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    // Update data model. Don't call moveRowAtIndexPath.
    [self reconfigureVisibleCells];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self configureCell:cell];
}

一些补充意见:

  1. cellForRowAtIndexPath 仅在表格 View 需要显示新单元格时调用。永远不会为可见单元格调用它。
  2. 当您的数据模型更改并且您需要将该更改传播到 UI 时,调用 moveRowAtIndexpath 是合适的。您的情况与此相反,即 UI 正在传播对您的数据模型的更改。所以您不会调用 moveRowAtIndexPath
  3. 我总是在 willDisplayCell 中重新配置单元格,因为在某些情况下, TableView 会在 cellForRowAtIndexPath 之后覆盖您的自定义设置。

关于swift - 如何在移动行后再次调用 cellForRowAtIndexPath?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14417524/

相关文章:

html - 在 webview 中快速显示图像

ios - 在 swift 中创建一个带有 for 循环的字典

ios - 在 Spritekit 中左右倾斜宇宙飞船

ios - 单元测试错误抛出在 block 中

ios - 从 NSDate 获取 UITableView 标题

ios - Swift iPad - 按钮不起作用

ios - UITableViewCell 披露指标位置

ios - 无法在容器 View 中填充 TableView

iphone - 不滚动的 UITableView header

iPhone:当 UITableView 滚动到 60 多个自定义单元格时应用程序崩溃