I am trying to create a UIView(A) containing 2 custom Views (B) in it
View B is setup using Autolayout Constraints and made in Interface Builder, including the constraints. A is added in the Nib of the viewController
B - UIImageView(Leading = 10, Trailing = 10, AlignVertically) - UITextField(Leading = 10, Trailing = 10, AlignVertically)
ViewController A(300x300, AlignHorizontally, AlignVertically)
In the ViewController I have A to be fixed at 300x300 and B1 and B2 has its Leading, Trailing, Top and Bottom pinned at 0. (which should make B1 and B2 to be 300x150, forgive me if I miss something out)
When loading View B I use the following code to load its 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
}
But when I try to run this I get the following warning including a crash:
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.
I have also tried adding the view as a property of View B and use the following code to add it to B
NSBundle.mainBundle().loadNibNamed("B", owner: self, options: nil)
self.addSubview(self.viewOfB);
the result of this is the view is added to the viewController, but it is not adopting any of the AutoLayoutConstraints from its own Nib.
Right now I have no idea how to add this view to the viewController's view including the constraints. What am I doing wrong? Is there a better way to do this?
PS: View A used to be custom too.
PPS: I am using Swift to do this, but I'm sure solutions in Objective-C works as well.