Reputation: 11991
Suppose I use Interface Builder to create UI in Storyboard with Auto Layout. Can I copy or move some constraints from one view to another?
Upvotes: 36
Views: 34125
Reputation: 9740
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:
myView
.xib
file > Open As
> Source Code
or open it in another editor (e.g. Sublime Text
)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
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>
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>
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"/>
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>
Upvotes: 18
Reputation: 4765
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.
Upvotes: 20
Reputation: 1254
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 :)
Upvotes: 18