Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embed Views in super view without losing autolayout constraints

Tags:

in an ios application, I have a custom UITableViewCell with a lot of views in it. I am using auto layout and setup all the constraints as I need.

But now I need to have a main view (in the content view) and put all the other views in it (some sort of a parent view to all).

This is an example of how my cell looks in the interface builder:

enter image description here

it has all the views setup with the constraints.

I know there is an xcode feature to embed selected views inside a parent view:

enter image description here

So I select all the view and select to embed them in a view. I get the following:

enter image description here

My Problem

Although the views are embedded correctly in a superview, the autolayout constraint were removed, and now I have to recreate them.

Is there a way I can put all the views inside a superview and have the same autolayout constraints without having to recreate them all? Thank you

like image 862
Y2theZ Avatar asked Mar 29 '14 23:03

Y2theZ


1 Answers

As mentioned in the comments above, this approach works well for me:

indiestack.com/2013/12/transplanting-constraints

In short, the approach is:

  1. Give your old superview a restorationId so you can easily identify it in the XML.
  2. Open the XIB/Storyboard you are working with in a text editor view.
  3. Copy and paste what is currently there into a backup file.
  4. Embed your content into a new superview using the storyboard. Do not set any new constraints yet.
  5. Give your new superview a restoration ID so you can easily identify it in the XML.
  6. Open up the current storyboard/XIB side by side with the old storyboard/XIB you backed up.
  7. Find the old container view in the backed up XML by searching for the restoration ID. Copy everything inside the <constraints></constraints> and <subviews></subviews> tags
  8. Find the new container view in the current XML and replace the content of its <constraints></constraints> and <subviews></subviews> tags with the copied content
  9. Go into the old XML and copy the ID of the old container.
  10. Go into the new XML, and replace the old ID you got from step 9 with the id of the new container everywhere inside the <constraints></constraints> you pasted in.
  11. Don't forget to add constraints to your new container that match the old container (in my case this was pinning the new container to all the edges of the super view).

Caveat: This will break any outlets to constraints you may have set up. Outlets to other things, views, etc... will be fine.

like image 51
gregkerzhner Avatar answered Sep 19 '22 11:09

gregkerzhner