我試圖創建一個包含2個自定義視圖(B)在其添加一個子類的UIView到筆尖與它的自動佈局約束
視圖B一個UIView(A)使用自動佈局約束,建立和Interface Builder中取得包括約束條件。的UIImageView(前導= 10,尾隨= 10,AlignVertically) - - 的UITextField(前導= 10,尾隨= 10,AlignVertically)
的ViewController A(A是在的viewController
B的筆尖 加入300x300,Align Horizontal,AlignVertically)
在ViewController中,我將A固定爲300x300和 B1和B2將其前導,尾隨,頂部和底部固定爲0.(這應該使B1和B2爲300x150,原諒我,如果我錯過了什麼)
當加載查看BI使用下面的代碼加載它的筆尖:
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:視圖A過去也是自定義的。
PPS:我正在使用Swift來做到這一點,但我確信Objective-C中的解決方案也適用。
看看這個教程同樣大小應該是有幫助的,以使用編程方式創建約束在快速 http://makeapppie.com/2014/07/26/the-swift-swift-tutorial-how-to-use-uiviews-with-auto-layout-programmatically/ – Signo 2014-09-26 13:15:40