I have a UITableView with multiple sections. Instead of the typical approach of using an array per section, I am using one array. Anyway, I am having trouble getting the current indexPath.row as if there was only one section in the tableview.

So pretty much what I am trying to do is as follows. If the section == 0, I just use the indexPath.row, but if the section > 0, I want to add up all the rows from the previous section and get the current row in the current section to get the total row number AS IF THE TABLEVIEW WAS ONLY ONE SECTION.

This is my current code and it just isn't working out, perhaps you guys will see what I am doing wrong. Please let me know:

if (indexPath.section == 0) {
        currentRow = indexPath.row;
    } else {
        NSInteger sumSections = 0;
        for (int i = 0; i < indexPath.section; i++) {
            int rowsInSection = [activitiesTable numberOfRowsInSection:i] + 1;
            sumSections += rowsInSection;
        }
        NSInteger row = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section].row + 1;
        currentRow = sumSections + row;
    }
有帮助吗?

解决方案

first you do not need the first if because it would not run through the for-next. Then you are adding one which is not necessary and then you can just add the indexPath.row like that:

    NSInteger sumSections = 0;
    for (int i = 0; i < indexPath.section; i++) {
        int rowsInSection = [activitiesTable numberOfRowsInSection:i];
        sumSections += rowsInSection;
    }
    currentRow = sumSections + indexPath.row;

其他提示

This is a version for swift 4.

var currentIndex = 0
var sumSections = 0;

for index in 0..<indexPath.section {
    let rowsInSection = self.tableView.numberOfRows(inSection: index)
    sumSections += rowsInSection
}

currentIndex = sumSections + indexPath.row;

Here is the method I am currently using in Swift 4 that works for me

var currentRow = 0
for section in 0..<indexPath.section {
        let rows = self.tableView.numberOfRows(inSection: section)
        currentRow += rows
}

currentRow += indexPath.row
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top