Get all indexPaths in a section

江枫思渺然 提交于 2020-01-13 03:54: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.


回答1:


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)



回答2:


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]
}



回答3:


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




回答4:


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)



回答5:


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)
    }
}


来源:https://stackoverflow.com/questions/50367280/get-all-indexpaths-in-a-section

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!