Dynamic UITableView height in UIPopoverController (contentSizeForViewInPopover)?

Valentin Radu picture Valentin Radu · Jun 11, 2011 · Viewed 13.8k times · Source

I have an ipad popover that contains an UITableView. After the table is populated, it usually has a few items in it only (4-5), so I'm looking for a way to resize the popover (contentSizeForViewInPopover) to the actual table height (the summed height of all its cells).

So, I do have the height but I'm not sure where to call contentSizeForViewInPopover, I did try to call it in: viewDidAppear and viewWillAppear but with no success since it seems that the table gets populated later and the actual height is only available later.

Any thoughts on this? Thanks!

EDIT: My cells have different heights based on the content they carry, I can't pre-calculate the height with noOfRows * cellHeight.

Answer

Sheepdogsheep picture Sheepdogsheep · Feb 15, 2012

I wanted to change the contentSizeForViewInPopover when my view appeared to match the UITableView and also when I call reloadData as I only call this when removing or adding rows or sections.

The following method calculates the correct height and width and sets the contentSizeForViewInPopover

-(void) reloadViewHeight
{
    float currentTotal = 0;

    //Need to total each section
    for (int i = 0; i < [self.tableView numberOfSections]; i++) 
    {
        CGRect sectionRect = [self.tableView rectForSection:i];
        currentTotal += sectionRect.size.height;
    }

    //Set the contentSizeForViewInPopover
    self.contentSizeForViewInPopover = CGSizeMake(self.tableView.frame.size.width, currentTotal);
}