Get all indexPaths in a section

2020-07-18 03:13发布

I need to reload the section excluding the header after I do some sort on my tableview data. That's to say I just want to reload all the rows in the section. But I don't find a easy way to make it after I search for a while.

reloadSections(sectionIndex, with: .none) not works here, for it will reload the whole section including the header, footer and all the rows.

So I need to use reloadRows(at: [IndexPath], with: UITableViewRowAnimation) instead. But how to get the whole indexPaths for the all the rows in the section.

5条回答
神经病院院长
2楼-- · 2020-07-18 03:34

Iterate over the index paths in a section using the numberOfRows inSection method of UITableView. Then you can build your IndexPath array:

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)
查看更多
冷血范
3楼-- · 2020-07-18 03:35

You can get the indexPaths for reloading like this…

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

There's no need to reload non-visible cells, as they will be updated when cellForRow(at indexPath:) is called

查看更多
forever°为你锁心
4楼-- · 2020-07-18 03:36

You can use below function get IndexPath array in a given section.

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

Or

func getAllIndexPathsInSection(section : Int) -> [IndexPath] {
    return tblList.visibleCells.map({tblList.indexPath(for: $0)}).filter({($0?.section)! == section}) as! [IndexPath]
}
查看更多
Luminary・发光体
5楼-- · 2020-07-18 03:43

You can get all the visible index paths directly, and then filter them however you want, i.e.

func reloadRowsIn(section: Int, with animation: UITableView.RowAnimation) {
    if let indexPathsToReload = indexPathsForVisibleRows?.filter({ $0.section == section }) {
        reloadRows(at: indexPathsToReload, with: animation)
    }
}
查看更多
Evening l夕情丶
6楼-- · 2020-07-18 03:52

In my opinion, you don't need reload whole cells in the section. Simply, reload cells which is visible and inside section you need to reload. Reload invisible cells is useless because they will be fixed when tableView(_:cellForRowAt:) is called.

Try my below code

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)
查看更多
登录 后发表回答