UITableViewSection Row Indices

2020-05-06 04:38发布

问题:

I have a UITableView with three sections (Friday, Saturday, Sunday) each with different data and a different number of rows. When selected, the selected row expands, but so do the rows in the other two sections with the same index. I only want the single selected row to expand.

Is there a way to also get the the section in my didSelectRowAtIndexPath method, and to use that in my heightForRowAtIndexPath method in order to keep all of the other rows at their unexpanded size?

The methods below are both in my UITableView subclass:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//[tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;
customCell *cell = [tableView cellForRowAtIndexPath:indexPath];

//Close row if tapped a second time
if(self.currentSelection == indexPath.row) {
    self.currentSelection = -1;
}
//Otherwise, expand row
else {
    self.currentSelection = indexPath.row;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
int rowHeight;
if ([indexPath row] == self.currentSelection) {
    rowHeight = 185;
} else rowHeight = 44;
return rowHeight;
}

回答1:

Save the index path as your selection instead of just the row. At the moment you are saving, say, row 2, and each section has a row 2, so that row is expanding in all sections.

You can compare index paths as follows:

if([indexPath1 isEqual:indexPath2])
    // Do your thing

Better yet, UITableView has an indexPathForSelectedRow property, so you don't even need your own variable to keep track of this:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
int rowHeight;
if ([indexPath isEqual:tableView.indexPathForSelectedRow]) {
    rowHeight = 185;
} else rowHeight = 44;
return rowHeight;
}


回答2:

Check NSIndexPath. This object contains section as property.