DiscoJunk
DiscoJunk

Reputation: 43

Count overall cell index for grouped UITableView?

I'm trying to create an index count for every cell in a grouped UITableView so I can store the cell values at correct positions in an array but I can't work out the math needed for it:

The index runs as follows, and my count needs to be:

indexPath.section = 0   
  indexPath.row = 0     cellIndex = 0
  indexPath.row = 1     cellIndex = 1
  indexPath.row = 2     cellIndex = 2
  indexPath.row = 3     cellIndex = 3
  indexPath.row = 4     cellIndex = 4

indexPath.section = 1
  indexPath.row = 0     cellIndex = 5
  indexPath.row = 1     cellIndex = 6
  indexPath.row = 2     cellIndex = 7
  indexPath.row = 3     cellIndex = 8

This is my equation so far but it's not working correctly:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger cellIndex = numberOfSections * indexPath.section + indexPath.row;
}

Upvotes: 1

Views: 196

Answers (3)

DiscoJunk
DiscoJunk

Reputation: 43

I figured out a simple way to achieve this:

//Number of cells before this
int cellsBefore = 0;
for(int i = indexPath.section - 1; i >= 0; i--) {
    cellsBefore += [tableView numberOfRowsInSection:i];
}
//Calculate cellIndex count
NSInteger cellIndex = cellsBefore + indexPath.row;

Upvotes: 1

Timothy Moose
Timothy Moose

Reputation: 9915

You could use TLIndexPathTools. The TLIndexPathDataModel class can automatically organize items into sections and there are numerous convenience APIs to simplify view controller code. For example, you would get the total number of items like this:

self.indexPathController.items.count;

There are several sample projects demonstrating different use cases. The JSON sample project demonstrates organizing JSON data into sections using a sectionNameKeyPath property similar to how NSFetchedResultsController works (except that items don't need to be pre-sorted by section with TLIndexPathTools). It is also possible to explicitly create sections, including empty ones, by creating TLIndexPathSectionInfo instances. See the Section Info sample project.

Upvotes: 0

Andrew
Andrew

Reputation: 1106

I think you should change numberOfSections * indexPath.section to numberOfCellsPerSection * indexPath.section. According to your comment of the answer, you can store the uitextfield value to the corresponding entity of the cell instead of using an array.

Upvotes: 0

Related Questions