Search code examples
iosobjective-cuitableviewnsindexpathuitableviewsectionheader

Rows Count In Section


In My Expandable UITableview number of section are 5 [SectionItems.count].

My goal is to number all cells in the sections from 1 to count of all rows (numbering should not respect sections).

enter image description here

this is my code for count rows

NSInteger count = 0;
for (NSInteger sec=0; sec < indexPath.section; sec++) {
    NSInteger rows = [tableView numberOfRowsInSection:sec];
    count += rows;
}
count += indexPath.row + 1;


NSArray *sect = [sectionItem objectAtIndex:indexPath.section];
cell.titleLbl.text = [NSString stringWithFormat:@"%ld %@",(long)count,[sect objectAtIndex:indexPath.row]];

But I got what you can see in next image:

enter image description here

The problem is that the first section (Versioning scheme) has a row, so those two numbers should be 2 and 3 instead of 1 and 2.

What am I doing wrong here?


Solution

  • The problem here must be that you check all currently visible rows. You should create one more array with cell numbers and then get them the same as you get text.

    Each time you update row data you should redo the numbering

    - (NSArray *)numberCells {
        NSArray *numbersArray = [[NSArray alloc] init];
        NSInteger num = 1;
        for (NSArray *ar in sectionItem) {
            NSArray *rowArray = [[NSArray alloc] init];
            for (id item in ar) {
                rowArray = [rowArray arrayByAddingObject:[NSNumber numberWithInteger:num]];
                num += 1;
            }
            numbersArray = [numbersArray arrayByAddingObject:rowArray];
        }
        return numbersArray;
    }
    

    Update array property when needed like this: myArray = [self numberCells]; then get cell number like this:

    NSArray *rowArray = [numbersArray objectAtIndex:indexPath.section];
    NSNumber *num = [rowArray objectAtIndex:indexPath.row];
    

    Good luck!