Dynamically resize a XIB's root view to the size of its contents with Autolayout Dynamically resize a XIB's root view to the size of its contents with Autolayout xcode xcode

Dynamically resize a XIB's root view to the size of its contents with Autolayout


How can I make the rootview of a XIB flexible so that it dynamically adjusts its size to match its contents?

Not possible Interface builder.

As the superview does not have any constraints there should be neither ambiguity nor conflicting constraints

Its not just a super view. Its also an objet in nib. We define simulated size for such views. This could be used to silence the errors. But again these are just simulated.

Is this rootView a view controllers view ? If yes i don't understand why are you trying to fix its withd to 280 and height to 168.

If this view is a custom view that you are going to add to another 'parent' view. Then you should change you simulated size to with 280 and height 168, and when adding this as subview you need to add two more constraints to position this rootview in the 'parent' view.


I had a same issue. I have a view in xib, which had dynamic content and it needed to fit into other superviews. so here is the answer how I achieved that

First you need to

myViewFromXib.translatesAutoresizingMaskIntoConstraints = false to prevent translating autoresizing mask into constraints. Then add subview superViewForMyViewFromXib.addSubview(myViewFromXib). And just add your constraints to superview like this:

NSLayoutConstraint.activate([            (myViewFromXib.topAnchor.constraint(equalTo: superViewForMyViewFromXib.topAnchor, constant: 0))!,            (myViewFromXib.bottomAnchor.constraint(equalTo: superViewForMyViewFromXib.bottomAnchor, constant: 0))!,            (myViewFromXib.leadingAnchor.constraint(equalTo: superViewForMyViewFromXib.leadingAnchor, constant: 0))!,            (myViewFromXib.trailingAnchor.constraint(equalTo: superViewForMyViewFromXib.trailingAnchor, constant: 0))!            ])superViewForMyViewFromXib.setNeedsLayout()


You can do this by editing the xib manually, for example to set a height constraint (in my case it was an inequality to set the minimum height):

  1. add a constraint to a subview for the height
  2. open the xib as a text file
  3. find the constraint you added (eg by Cmd-F'ing to the value of the height)
  4. cut and paste it into the root view's constraint section
  5. Open the xib in interface builder again
  6. The constraint appears and you can edit it like normal.