Is it possible to copy constraints from one view to another? Is it possible to copy constraints from one view to another? ios ios

Is it possible to copy constraints from one view to another?


If you are using interface builder, some constraints will be automatic copied if you use the cmd-c or edit/copy: the ones that include the copying view hierarchy. Otherwise, no, you can't. Copy the whole view if you want to preserve the constraints.


Here's my hack to get ALL the constraints to copy: I have a small view within my main view that I want to copy over to another view controller, in order to do this I copy over the entire main view into the new view controllers main view. I then drag my small view (on side hierarchy) into the main view of my new controller and then just deleted the old main view that I don't need. This way you keep all the constraints for the items within the small view.

Hope this helps :)


You can if you understand and learn how the XML of the .xib files works. I got pretty used to them and so I was able to move a view with its constraints into another view.

I'll try to explain it step by step:

  1. Create an outlet for it: myView
  2. Right click the .xib file > Open As > Source Code or open it in another editor (e.g. Sublime Text)
  3. Search myView and you'll find something like:

    <outlet property="myView" destination="i5M-Pr-FkT" id="sfx-zR-JGt"/>

    and copy the destination attribute's value

  4. Search the copied id (i5M-Pr-FkT) and one of the results will be a view tag:

    <view contentMode="scaleToFill" id="i5M-Pr-FkT"> <!-- 1 -->    ...</view>
  5. Cut and paste this whole view tag in the needed view's subviews tag:

    <view contentMode="scaleToFill" id="Ovp-8Y-qHZ"> <!-- 2 -->    <subviews>        <view contentMode="scaleToFill" id="i5M-Pr-FkT"> <!-- 1 -->            ...        </view>    </subviews></view>
  6. Continue searching for the copied id and you'll find some constraints that have it like:

    <constraint firstItem="w7M-JQ-JWD" firstAttribute="leading" secondItem="i5M-Pr-FkT" secondAttribute="leading" id="EwH-B1-XWY"/>
  7. You need to move this into the constraints tag of the lowest common ancestor of both superviews (the old one and the new one):

    <view contentMode="scaleToFill" id="rK2-sE-P0d"> <!-- 3 -->    <subviews>        <view contentMode="scaleToFill" id="Ovp-8Y-qHZ"> <!-- 2 -->            <subviews>                <view contentMode="scaleToFill" id="i5M-Pr-FkT"> <!-- 1 -->                    ...                </view>            </subviews>        </view>    </subviews>    <constraints>        <constraint firstItem="w7M-JQ-JWD" firstAttribute="leading" secondItem="i5M-Pr-FkT" secondAttribute="leading" id="EwH-B1-XWY"/>    </constraints></view>


matomo