从 nib 文件加载 UIView 时, View 通常具有 translatesAutoresizingMastIntoConstraints
设置为是。
因此,您无法向 View 添加顶级约束(例如宽度和高度)。
在过去,我已经能够生成一个顶级 View ,它允许我创建顶级约束,并设置 translatesAutoresizingMastIntoConstraints
否。
从 Nib 加载 UIView 而不对其进行子类化时,如何获得这种行为?
最佳答案
更新:尽管您可以创建受约束的 View ,但我不会推荐它,因为很难区分两者之间的区别。如果您需要修改或重新创建 View ,您可能会忘记它是一个受约束的 View 并意外地重新创建了一个静态 View 。因此,我建议您将顶级 View 保留为静态 View ,并在从 Nib 创建它们后手动更新它们:
let view = UINib(nibName: "ABCView", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! UIView
view.translatesAutoresizingMaskIntoConstraints = false
如果 View 需要固有内容大小,请覆盖 intrinsicContentSize ,或通过 nib 文件定义其宽度和/或高度,只需添加一个“调整大小” subview ,该 subview 固定到顶级 View (即静态 View )的顶部、底部、尾随和前导约束,并具有宽度和/或高度限制。
这似乎是一个未记录的 Xcode 功能(在 Xcode 6 和 Xcode 7.1 上测试)。
我将使用以下术语:
translatesAutoresizingMaskIntoConstraints
设置为是。 translatesAutoresizingMaskIntoConstraints
设置为否。 首先让我们来看看它们的一些区别......
静态 View
.xib 内容:
<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>
更多信息:
<UIView: 0x7fec19ccb1b0; frame = (0 0; 320 439); autoresize = W+H; layer = <CALayer: 0x7fec19ccae80>>
约束 View
.xib 内容:
<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>
更多信息:
<UIView: 0x7f9503eb2ba0; frame = (0 0; 320 439); autoresize = RM+BM; layer = <CALayer: 0x7f9503e9dc80>>
细微差别:
<autoresizingMask ...
元素。 如何创建新的约束 View :
如何将现有静态 View 转换为可约束 View :
如何将现有的约束 View 转换回静态 View :
关于uiview - 如何在 Interface Builder .xib 文件中添加顶级约束并禁用 translatesAutoresizingMaskIntoConstraints,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25902335/