When loading a UIView from a nib file, the view usually has translatesAutoresizingMastIntoConstraints
set to YES.
As a consequence, you cannot add top level constraints to the view (e.g. width and height).
In the past I have been able to generate a top level view which does allow me to create top level constraints, and sets translatesAutoresizingMastIntoConstraints
to NO.
How can I get this behavior when loading a UIView from a nib without subclassing it?
Update: Although you can create constrainable views, I wouldn't recommend it because it's extremely hard to tell the difference between the two. If you ever need to modify or recreate the view, you may forget that it was a constrainable view and accidentally recreate a static view. Therefore, I would recommend that you leave top level views as static views, and manually update them after creating them from a nib:
let view = UINib(nibName: "ABCView", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! UIView
view.translatesAutoresizingMaskIntoConstraints = false
If the view needs an intrinsic content size, either override intrinsicContentSize, or define its width and/or height via the nib file, by simply add a "sizing" subview that is pinned to the top level view's (i.e. the static view's) top, bottom, trailing, and leading constraints, and has a width and/or height constraint.
This seems to be an undocumented Xcode feature (tested on Xcode 6, and Xcode 7.1).
I will use the following terms:
translatesAutoresizingMaskIntoConstraints
set to YES.translatesAutoresizingMaskIntoConstraints
set to NO.First let's take a look at some of their differences...
.xib contents:
<view contentMode="scaleToFill" id="bU6-qJ-x7d" userLabel="STATIC">
<rect key="frame" x="0.0" y="0.0" width="320" height="439"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
<nil key="simulatedStatusBarMetrics"/>
<freeformSimulatedSizeMetrics key="simulatedDestinationMetrics"/>
<point key="canvasLocation" x="687" y="37.5"/>
</view>
More info:
<UIView: 0x7fec19ccb1b0; frame = (0 0; 320 439); autoresize = W+H; layer = <CALayer: 0x7fec19ccae80>>
.xib contents:
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="0G6-nE-8IZ" userLabel="CONSTRAINABLE">
<rect key="frame" x="0.0" y="0.0" width="320" height="439"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<nil key="simulatedStatusBarMetrics"/>
<freeformSimulatedSizeMetrics key="simulatedDestinationMetrics"/>
<point key="canvasLocation" x="687" y="-455.5"/>
</view>
More info:
<UIView: 0x7f9503eb2ba0; frame = (0 0; 320 439); autoresize = RM+BM; layer = <CALayer: 0x7f9503e9dc80>>
<autoresizingMask ...
element.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With