Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get row number of UITableview with multiple sections

I have a UITableView, with multiple sections in it, and each section has multiple rows. I want to get the row number of selected cell with respect to the entire table and not the section only.

example:

  1. I have two sections in the UITableView, section 1 has 3 rows and section 2 has 5 rows.
  2. When I select sections 2's 2nd row, I should get the 5 as the row number in didSelectRowAtIndexPath method, rather than getting 2 as the row number (which is with respect to the section).

I tried to get the row number myself by doing the following, but it does not seem to work:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];

NSLog(@"%d",indexPath.row);

int theRow =  indexPath.row;

NSLog(@"%d",theRow);
}

I was thinking of storing the row number in an intvariable, and then add row numbers to it myself, but the code crashes when trying to store indexpath.row in theRow .

Please help. Thank you

like image 895
Hyder Avatar asked Jun 06 '13 17:06

Hyder


2 Answers

NSInteger rowNumber = 0;

for (NSInteger i = 0; i < indexPath.section; i++) {
    rowNumber += [self tableView:tableView numberOfRowsInSection:i];
}

rowNumber += indexPath.row;
like image 186
Wain Avatar answered Oct 28 '22 02:10

Wain


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
}
like image 9
PJeremyMalouf Avatar answered Oct 28 '22 01:10

PJeremyMalouf