19

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.

JJD
  • 50,076
  • 60
  • 203
  • 339

2 Answers2

27

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.

jrturton
  • 118,105
  • 32
  • 252
  • 268
  • Which event would you wait for to know that the layout manager has done its job, meaning enlarging or shrinking the container view? – JJD Nov 13 '12 at 20:08
  • In iOS, it would be viewDidLayoutSubviews in the view controller, but I'm not sure of the cocoa equivalent. Is there a reason you'd need to know? – jrturton Nov 13 '12 at 21:56
  • I am using the Autolayout as part of a larger composition which itself does not use Autolayout. Therefore, I need to rearrange the composition parts when the layout manager did finish its work. – JJD Nov 14 '12 at 00:18
  • Oh ok, painful. I wouldn't like to say really, I've not done OS X development for a good few years. – jrturton Nov 14 '12 at 08:12
  • 2
    I would like to 1) thank you for this answer, and 2) stress the importance of number 2 and 4. I have been struggling with this because my subviews (`UIButton`s) showed, but couldn't be tapped. Turns out the superview had no size (that is, 0x0) because the spacing to superview constraints were missing. – Scott Berrevoets May 30 '13 at 19:09
  • You should include `TranslatesAutoresizingMaskIntoConstraints = false` on the views to be resized. – N_A Sep 06 '14 at 02:15
  • @ScottBerrevoets I had the same problem.. the button could be seen but couldnt be touched. Took me a whole day to figure this out – MK Yung Jun 22 '15 at 16:13
2

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

Chris
  • 2,727
  • 2
  • 27
  • 28