Autolayout a UIScrollView to fit content including subviews and grouped tables

我与影子孤独终老i 提交于 2019-12-19 09:04:44

问题


I am trying to present information about an object grouped into sections. It may be long, so each section uses a view to visually separate the areas and it is all in a scroll view.

The first subview has a text field that does resize to fit the text, and its parent view also resizes to fit the text field.

The second subview has a grouped table to display data. I want all of the data in the table to appear and there should be no table scrolling.

The third subview has more information but its contents are an empty view for the purposes of this demo. In the real app I may add an arbitrary number of custom subviews.

What I'm finding is that the first subview resizes appropriately but I cannot find the combination of layout constraints that will make the second subview size to fit the table and move the third view down.

What do I need to do to make the scroll view fit its contents, when the sub view's contents may resize? The table view is filling the available space in the parent view, but the parent view is not expanding to fit. I note that the third view has a top space constraint to the superview, not just to the view above it. That's visible in the screenshot below


回答1:


I found a solution that like most solutions, seems obvious in retrospect.

I think my problem is that the interior tableview had no fixed height and since it also a scrollview, was trying to fit whatever was assigned instead of expanding to fit the interior content. I was able to solve my problem by adding a fixed height constraint in IB and hooking it up to an outlet in my view controller. Then in the controller:

-(void) viewWillLayoutSubviews{
    [self.tableView layoutIfNeeded];
    self.tableViewHeightConstraint.constant = self.tableView.contentSize.height;
}

Derp. In summary the table view needed a height so I set one.

Here's a screenshot, note the fixed height constraint on the right hand side:



来源:https://stackoverflow.com/questions/16096021/autolayout-a-uiscrollview-to-fit-content-including-subviews-and-grouped-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!