2

I am trying to create a UITableViewController which has a UICollectionViewController as its tableHeaderView. This collection view will vary in height depending on what's (re)loaded.

Here is the basic layout. enter image description here

And here it is in action:

enter image description here

As of now, I can get the tableHeaderView to resize by calculating the childViewController's height based on the number of cells then setting its preferredContentSize property.

- (void)reloadCollectionView {
    // Calculate size based on static cell height and layout
    _cellCount = arc4random_uniform(40) + 1;
    NSUInteger h = ceil(_cellCount / 2.0);

    // This informs the parent view controller of the size change
    self.preferredContentSize = CGSizeMake(self.collectionView.bounds.size.width, 20 * h);

    // Load the new number of cells
    [self.collectionView reloadData];
}

Meanwhile, in the parent view controller, I override this method then update the containerView frame like so:

- (void)preferredContentSizeDidChangeForChildContentContainer:(id<UIContentContainer>)container {
    [super preferredContentSizeDidChangeForChildContentContainer:container];

    // Make new CGSize to update tableHeaderView's height and reassign tableHeaderView property (required for UI refresh)
    CGSize size = [container preferredContentSize];
    _tableHeaderContainerView.frame = CGRectMake(0, 0, self.view.bounds.size.width, size.height);
    self.tableView.tableHeaderView = _tableHeaderContainerView;
}

This works, but this stinks. I'd like autolayout to take care of this for me but I cannot figure out how/where to get parentViewController.tableHeaderContainerView to automatically resize to fit its content view controller.

The code that I inherited and am rewriting uses a UIView/nib for the table header view but this implementation is messy as the parent view controller has too much to do already. It seems like moving this to its own view controller is the way to go, but I have to tackle this resizing problem first.

VaporwareWolf
  • 10,143
  • 10
  • 54
  • 80

1 Answers1

0

You could use KVO to monitor the collection view's contentSize and set the preferredContentSize to it when it changes.

malhal
  • 26,330
  • 7
  • 115
  • 133