Accordion table cell – How to dynamically expand/contract uitableviewcell?

The Apple way to do is quite simple.

First, you’ll need to save the selected indexPath row:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   self.selectedRowIndex = [indexPath retain];
   [tableView beginUpdates];
   [tableView endUpdates];
}

I’ll explain the begin/end updated part later.

Then, when you have the currently selected index, you can tell the tableView that it should give that row more space.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
   //check if the index actually exists
   if(selectedRowIndex && indexPath.row == selectedRowIndex.row) {
        return 100;
   }
   return 44;
}

This will return height 100 for the selected cell.

Now we can go back to the begin/end updates. That block triggers the reload of all tableView geometry. Moreover, that block is animated, which eventually gives the impressions of the row expanding.

Leave a Comment