使用Autolayout Constraints设置View B,包括约束条件,并在Interface Builder中制作。将A添加到viewController的Nib中。
B - UIImageView(Leading = 10,Trailing = 10,AlignVertically) - UITextField(Leading = 10,Trailing = 10,AlignVertically)
ViewController A(300x300,AlignHorizontally,AlignVertically)
在ViewController中,我将A固定为300x300, B1和B2的Leading,Trailing,Top和Bottom固定为0。(这应该使B1和B2成为300x150,请原谅我是否遗漏了什么)
加载View B时,我使用以下代码加载其Nib:
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.
我还尝试将该视图作为View B的属性添加,并使用以下代码将其添加到B中。
NSBundle.mainBundle().loadNibNamed("B", owner: self, options: nil)
self.addSubview(self.viewOfB);
这样做的结果是将视图添加到viewController中,但它没有采用任何来自自己Nib的AutoLayout约束。
现在我不知道如何将此视图添加到viewController的视图中,包括其约束条件。我做错了什么?有更好的方法吗?
PS:View A 也曾经是自定义的。
PPS:我使用Swift来完成此操作,但我相信Objective-C的解决方案也适用。