4

在对表格视图数据进行某种排序后,我需要重新加载不包括标题的部分。也就是说我只想重新加载该部分中的所有行。但是经过一段时间的搜索,我没有找到一种简单的方法。

reloadSections(sectionIndex, with: .none)在这里不起作用,因为它将重新加载整个部分,包括页眉、页脚和所有行。

所以我需要reloadRows(at: [IndexPath], with: UITableViewRowAnimation)改用。但是如何获取该部分中所有行的整个 indexPaths。

4

5 回答 5

8

您可以在给定部分中使用以下函数获取 IndexPath 数组。

func getAllIndexPathsInSection(section : Int) -> [IndexPath] {
    let count = tblList.numberOfRows(inSection: section);        
    return (0..<count).map { IndexPath(row: $0, section: section) }
}

或者

func getAllIndexPathsInSection(section : Int) -> [IndexPath] {
    return tblList.visibleCells.map({tblList.indexPath(for: $0)}).filter({($0?.section)! == section}) as! [IndexPath]
}
于 2018-05-16T09:45:02.560 回答
7

在我看来,您不需要在该部分中重新加载整个单元格。简单地说,重新加载您需要重新加载的可见和内部部分的单元格。重新加载不可见的单元格是没有用的,因为它们会在tableView(_:cellForRowAt:)被调用时被修复。

试试我下面的代码

var indexPathsNeedToReload = [IndexPath]()

for cell in tableView.visibleCells {
  let indexPath: IndexPath = tableView.indexPath(for: cell)!

  if indexPath.section == SECTION_INDEX_NEED_TO_RELOAD {
    indexPathsNeedToReload.append(indexPath)
  }
}

tableView.reloadRows(at: indexPathsNeedToReload, with: .none)
于 2018-05-16T09:45:39.907 回答
6

您可以像这样获取用于重新加载的 indexPaths...</p>

let indexPaths = tableView.visibleCells
    .compactMap(tableView.indexPath)
    .filter { $0.section == SECTION }

无需重新加载不可见的单元格,因为它们会在cellForRow(at indexPath:)调用时更新

于 2018-05-16T09:55:26.410 回答
1

使用 UITableView 的 numberOfRows inSection 方法遍历节中的索引路径。然后你可以构建你的 IndexPath 数组:

var reloadPaths = [IndexPath]()
(0..<tableView.numberOfRows(inSection: sectionIndex)).indices.forEach { rowIndex in
    let indexPath = IndexPath(row: rowIndex, section: sectionIndex)
    reloadPaths.append(indexPath)
}
tableView.reloadRows(at: reloadPaths, with: UITableViewRowAnimation)
于 2018-05-16T09:53:04.327 回答
-1

您可以直接获取所有可见的索引路径,然后根据需要过滤它们,即

func reloadRowsIn(section: Int, with animation: UITableView.RowAnimation) {
    if let indexPathsToReload = indexPathsForVisibleRows?.filter({ $0.section == section }) {
        reloadRows(at: indexPathsToReload, with: animation)
    }
}
于 2019-01-16T22:34:16.347 回答