Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize a parent view based on the size of subviews layouted with Autolayout

I am preparing a custom view which looks similar to the example shown in the screenshot. I add all user interface components (labels, text fields, radio buttons, ..) at runtime. To position the elements I use Autolayout constraints. This part works fine so far.

Custom View

The number of elements varies from context to context. I wonder how I could use Autolayout constraints to dynamically resize the parent view (most likely the height of the view). The view constraints therefore should consider the height and margins defined for the currently attached subviews.

like image 433
JJD Avatar asked Oct 24 '12 14:10

JJD


2 Answers

I've done this with the following setup:

  • the container view has no height constraint
  • the top subview has a spacing constraint from the top of the container view
  • the contained views all have spacing constraints between them
  • the bottom view has a spacing constraint to the bottom of the container view

The auto layout system satisfies these constraints by resizing the container to fit its contents.

Of course, you need to dynamically set the constraints as you alter the contents.

like image 150
jrturton Avatar answered Oct 26 '22 19:10

jrturton


If you are use NSStackView then make sure you don't set a constraint for it's height and width and make sure all sides are anchored.

enter image description here

Also make sure that you set the content Hugging property to 1000.

enter image description here

like image 40
Chris Avatar answered Oct 26 '22 19:10

Chris