【发布时间】:2014-09-21 14:13:18
【问题描述】:
我正在尝试创建一个 UIView(A),其中包含 2 个自定义视图 (B)
视图 B 是使用 Autolayout 约束设置并在 Interface Builder 中制作的,包括约束。在viewController的Nib中添加了A
B - UIImageView(前导 = 10,尾随 = 10,垂直对齐) - UITextField(Leading = 10, Trailing = 10, AlignVertically)
视图控制器 A(300x300,水平对齐,垂直对齐)
在 ViewController 中,我将 A 固定在 300x300 和 B1 和 B2 的前导、尾随、顶部和底部固定为 0。(这应该使 B1 和 B2 为 300x150,如果我遗漏了什么,请见谅)
加载视图 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.
我也尝试将视图添加为视图 B 的属性,并使用以下代码将其添加到 B
NSBundle.mainBundle().loadNibNamed("B", owner: self, options: nil)
self.addSubview(self.viewOfB);
这样做的结果是视图被添加到 viewController,但它没有采用任何来自它自己的 Nib 的 AutoLayoutConstraints。
现在我不知道如何将此视图添加到 viewController 的视图中,包括约束。我究竟做错了什么?有没有更好的方法来做到这一点?
PS:View A 以前也是自定义的。
PPS:我正在使用 Swift 来执行此操作,但我确信 Objective-C 中的解决方案也可以。
【问题讨论】:
-
看看这个教程应该会有所帮助,以便在swift中使用以编程方式创建的约束makeapppie.com/2014/07/26/…
标签: ios iphone interface-builder autolayout