我正在尝试创建一个 UIView(A),其中包含 2 个自定义视图 (B)
视图 B 使用自动布局约束进行设置,并在 Interface Builder 中制作,包括约束。在viewController的Nib中添加A
乙
- UIImageView(前导 = 10,尾随 = 10,垂直对齐)
- UITextField(前导 = 10,尾随 = 10,垂直对齐)
视图控制器
A(300x300,水平对齐,垂直对齐)
在 ViewController 中,我将 A 固定为 300x300 并且
B1 和 B2 的前导、尾随、顶部和底部固定为 0。(这应该使 B1 和 B2 为 300x150,如果我遗漏了什么,请原谅)
加载视图 B 时,我使用以下代码加载其笔尖:
override func awakeAfterUsingCoder(aDecoder: NSCoder!) -> AnyObject! {
if self.subviews.count == 0 {
let bundle = NSBundle(forClass: self.dynamicType)
var view = bundle.loadNibNamed("B", owner: nil, options: nil)[0] as B
view.setTranslatesAutoresizingMaskIntoConstraints(false)
let constraints = self.constraints()
self.removeConstraints(constraints)
view.addConstraints(constraints)
return view
}
return self
}
但是当我尝试运行它时,我收到以下警告,包括崩溃:
The view hierarchy is not prepared for the constraint: <NSLayoutConstraint:0x7f897ad1acc0 V:[TestProject.B:0x7f897af73840(300)]>
When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. Break on -[UIView _viewHierarchyUnpreparedForConstraint:] to debug.
我还尝试将视图添加为视图 B 的属性,并使用以下代码将其添加到 B
NSBundle.mainBundle().loadNibNamed("B", owner: self, options: nil)
self.addSubview(self.viewOfB);
这样做的结果是视图被添加到 viewController,但它没有采用自己 Nib 中的任何自动布局约束。
现在我不知道如何将此视图添加到视图控制器的视图(包括约束)。我究竟做错了什么?有一个更好的方法吗?
PS:视图A曾经也是自定义的。
PPS:我使用 Swift 来做到这一点,但我确信 Objective-C 中的解决方案也可以工作。