zakdances
zakdances

Reputation: 23735

Adjust height of Storyboard-created UITableview to height of its contents

I've dragged a table view into my storyboard scene, but its height is static and won't adjust based on how many cells it contains unless I manually adjust it in storyboard. How can I get this table to adjust its own height based on the total height of its contents?

Upvotes: 0

Views: 3129

Answers (1)

mbm29414
mbm29414

Reputation: 11598

You're going to have to do some version of this:

  1. Figure out how many cells will be displayed
  2. Figure out the height for each cell
  3. Do the math and set the height of the UITableView

Before you get mad (since I know that's pretty obvious), let me follow up with this:

  1. If you know for sure how many cells will be displayed all the time (and it's a static value), you can just manually adjust the height in Interface Builder.
  2. If you don't know for sure (which I'm guessing is the case, based on your question), you'll have to do #'s 1 thru 3 above at runtime. Then, because UITableView is a subclass of UIView, you can simply adjust its frame property.

For example:

  1. I've got 7 cells.
  2. Cells 1, 3 and 5 (indices 0, 2 and 4) are 20 pixels tall.
  3. Cells 2, 4, 6 and 7 (indices 1, 3, 5 and 6) are 30 pixels tall.
  4. I need a total display height of 180 pixels (you might actually need to play with this because of separators, etc..)
  5. So, I can just call:

CGFloat newHeight = ... // Whatever you calculate
CGRect currentFrame = [[self MyTableView] frame];  
[[self MyTableView] setFrame:CGRectMake(
                 currentFrame.origin.x,
                 currentFrame.origin.y,
                 currentFrame.size.width,
                 newHeight)
 ];

If you want to get really fancy, you can animate the change by wrapping it in a [UIView animationWithDuration:] block.

Hope this helps!


Update/Edit

Here's a kludgy way to do it... it works, but I'm sure there's a better way to do it. I do not claim this to be the best/fastest/most efficient way. This is more to show a principle. ;-)

- (CGFloat)totalHeightNeededForTableView:(UITableView *)tv {
    CGFloat retVal = 0;

    int sectionCount = [self numberOfSectionsInTableView:tv];
    int rowCount = 0;
    NSIndexPath *path = nil;
    for (int i = 0; i < sectionCount; i = i + 1) {
        rowCount = [self tableView:tv numberOfRowsInSection:i];
        for (int j = 0; j < rowCount; j = j + 1) {
            path = [NSIndexPath indexPathForRow:j inSection:i];
            retVal = retVal + [self tableView:tv heightForRowAtIndexPath:path];
        }
    }
    return retVal;
}

Upvotes: 1

Related Questions