Search code examples
iosuitableviewsections

indexpath.row keeps resetting after I introduced sections


I added sections to my UITableview that are generated dynamically. I have a nice little chunk of code that works out which index to place the section headers at. So my numberOfSectionsInTableView and numberOfRowsInSection code works great.

Problem is my tableview looks like this, say my numberOfRowsInSection returns 2, 3, 5:

-==A==-
Aaron
Alex
-==B==-
Aaron
Alex
Alfred
-==C==-
Aaron
Alex
Alfred
Bart
Casey

So basically every time a new section begins, the indexPath.row resets back to 0?

Is there a way around this? Or do I have to tediously maintain which indexPath.row is needed for each cell myself?

Right now it looks like I have to loop through my array of names, work out which indexPath.section I am in, then go and count how many letters per section and calculate an offset.


Solution

  • an indexPath contains a row and a section. you can calculate the absolute row by adding the previous sections and its rows:

    NSInteger absoluteRow = indexPath.row;
    
    for(int section = 0; section < indexPath.section; ++section)
    {
        absoluteRow += [tableView numberOfRowsInSection:section];
    }
    

    another (in my opinion better) way is so use an two dimensional array as data structure. the array contains sections and every section contains rows of the section. you can load data by using:

    [[array objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];