Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all indexPaths in a section

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.

like image 431
LF00 Avatar asked Nov 30 '22 14:11

LF00


2 Answers

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]
}
like image 109
PPL Avatar answered Dec 03 '22 04:12

PPL


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)
like image 33
trungduc Avatar answered Dec 03 '22 04:12

trungduc