Search code examples
iosobjective-cuitableviewios5ios6

Resize UITableView's height to be as high as it needs to fit only total content size


So I am having a very basic issue. I have this UITableView within a view, and I would like to make this table's height as high as it needs to be to display ALL the rows within the table. Therefore, I don't want to be able to scroll, I just want all the rows to appear. (The rows are dynamic in quantity and height).

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGSize cellSize = [[[_stepsArray objectAtIndex:indexPath.row]content] sizeWithFont:[UIFont boldSystemFontOfSize:18.0f] constrainedToSize:CGSizeMake(528.0f, CGFLOAT_MAX)lineBreakMode:NSLineBreakByWordWrapping];
    return cellSize.height;
}

If there are 20 rows, the table will be very high, but if there is only 1 row, it will be very small and the other content will not appear 19 rows below.


Solution

  • if I understand it correctly, you should be able to add up the height for each row and adjust the tableview height based on that:

    CGFloat tableHeight = 0.0f;
    for (int i = 0; i < [_stepsArray count]; i ++) {
        tableHeight += [self tableView:self.tableView heightForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
    }
    self.tableView.frame = CGRectMake(self.tableView.frame.origin.x, self.tableView.frame.origin.y, self.tableView.frame.size.width, tableHeight);
    

    you can do this immediately after [tableView reloadData]