allaire
allaire

Reputation: 6045

UIContainerView height of content (embedded UITableViewController)

I currently have a UITableViewController embedded in a UIContainerView in Interface Builder. Is there a way to set the height of the UIContainerView to the content's height (using prototype cells)? Basically, what I want is to have a UIScrollView around my UIContainerView, and set some AutoLayout rules to my UIContainerView so that the height gets calculated from the number of cells inside, and the parent UIScrollView adjusts accordingly its scroll area.

Edit

Thanks to the great answers, ended up changing the frame height using this code:

    alarmsTableViewController.view.layoutIfNeeded()
    println(alarmsTableViewController.tableView.contentSize.height)
    alarmsContainerView.frame.size.height = alarmsTableViewController.tableView.contentSize.height

Upvotes: 1

Views: 960

Answers (2)

Mike Sand
Mike Sand

Reputation: 2770

Programmatic intervention is required: UITableViews are of course UIScrollViews, and nested scrollviews aren't going to be able to size themselves in AutoLayout. It's a legitimate ambiguity, because AutoLayout won't know to make the frame smaller and require more scrolling or the frame bigger and less scrolling. In your case, you want the latter with no scrolling.

The simplest way to solve this is to create a constraint for the height of the TableView (or its container view). This will act on the frame of the tableView, and if set to larger than the content size in any direction (only vertical in tableviews) the scroll view won't scroll. Best add it/modify it in the view that contains the tableView. Then access the table view's contentSize property. The actual code is very simple:

-(void)updateViewConstraints {
    self.tableViewHeightLayoutConstraint.constant = self.tableviewInMyScrollView.contentSize.height;
    [super updateViewConstraints];
}

If everything else in the scrollview has heights & widths that are fixed by the time the AutoLayout engine operates, this should automatically size the scrollview for its content.

Upvotes: 1

aramusss
aramusss

Reputation: 2401

What i do in my projects is inside -(void)updateViewConstraints on your ViewController update a constraint given by an IBOutlet depending on number of cells inside the tableView. For example:

-(void)updateViewConstraints{
   float newHeigh = ([self.array count] + 1) * 84;
   self.topViewHeightConstraint.constant = newHeigh + 540;
   [super updateViewConstraints];
}

Upvotes: 1

Related Questions