Get row number of UITableview with multiple sections
Here is a Swift adaption of the above answer by Wain
class func returnPositionForThisIndexPath(indexPath:NSIndexPath, insideThisTable theTable:UITableView)->Int{
var i = 0
var rowCount = 0
while i < indexPath.section {
rowCount += theTable.numberOfRowsInSection(i)
i++
}
rowCount += indexPath.row
return rowCount
}
Here's a cleaner implementation of this concept in Swift:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->
var rowNumber = indexPath.row
for i in 0..<indexPath.section {
rowNumber += self.tableView.numberOfRowsInSection(i)
}
// Do whatever here...
}
I had a big data set and the previous answers using for loops was causing performance issues for me in the lower sections. I ended up doing the calculating beforehand and sped things up a bit.
private var sectionCounts = [Int:Int]()
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let number = fetchedResultsController.sections?[section].numberOfObjects ?? 0
if section == 0 {
sectionCounts[section] = number
} else {
sectionCounts[section] = number + (sectionCounts[section-1] ?? 0)
}
return number
}
func totalRowIndex(forIndexPath indexPath: NSIndexPath) -> Int {
if indexPath.section == 0 {
return indexPath.row
} else {
return (sectionCounts[indexPath.section-1] ?? 0) + indexPath.row
}
}
NSInteger rowNumber = 0;
for (NSInteger i = 0; i < indexPath.section; i++) {
rowNumber += [self tableView:tableView numberOfRowsInSection:i];
}
rowNumber += indexPath.row;