I have a table with n sections. Each section contains one row. How to create the index path for the table?
There is a method that allows to create index path for all visible rows [self.tableView indexPathsForVisibleRows]
I need something similar like indexPathsForAllRows
I need all this to update only the data in the table, because method [self.tableView reloadData];
updates all the table with headers and footers. That's why i have to use reloadRowsAtIndexPaths
This code will give you complete indices:
extension UITableView {
func allIndexes() -> [IndexPath] {
var allIndexes: [IndexPath] = [IndexPath]()
let sections = self.sectionCount() ?? 0
if sections > 1 {
for section in 0...sections-1 {
let rows = self.rowCount(section: section) ?? 0
if rows > 1 {
for row in 0...rows-1 {
let index = IndexPath(row: row, section: section)
allIndexes.append(index)
}
} else if rows == 1 {
let index = IndexPath(row: 0, section: section)
allIndexes.append(index)
}
}
} else if sections == 1 {
let rows = self.rowCount(section: 0) ?? 0
if rows > 1 {
for row in 0...rows-1 {
let index = IndexPath(row: row, section: 0)
allIndexes.append(index)
}
} else if rows == 1 {
let index = IndexPath(row: 0, section: 0)
allIndexes.append(index)
}
}
return allIndexes
}
}
Here is the solution in Swift 3
func getAllIndexPaths() -> [IndexPath] {
var indexPaths: [IndexPath] = []
// Assuming that tableView is your self.tableView defined somewhere
for i in 0..<tableView.numberOfSections {
for j in 0..<tableView.numberOfRows(inSection: i) {
indexPaths.append(IndexPath(row: j, section: i))
}
}
return indexPaths
}
I made a UITableView
extension based on @Vakas answer. Also the sections and rows have to be checked for > 0
to prevent crashes for empty UITableView
s:
extension UITableView{
func getAllIndexes() -> [NSIndexPath] {
var indices = [NSIndexPath]()
let sections = self.numberOfSections
if sections > 0{
for s in 0...sections - 1 {
let rows = self.numberOfRowsInSection(s)
if rows > 0{
for r in 0...rows - 1{
let index = NSIndexPath(forRow: r, inSection: s)
indices.append(index)
}
}
}
}
return indices
}
}
You don't need reload all the rows. You only need to reload the visible cells (that is why indexPathsForVisibleRows
exists).
The cells that are off-screen will get their new data in cellForRowAtIndexPath:
once they become visible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With