[英]Constraining instantiated UIView from NIB to other UIView
我在向從NIB到另一個UIView的新實例化UIView添加約束時遇到問題。
我想做的確切是這樣的:
我可以在第一個UIView中添加第二個UIView,因為我可以看到它,但是約束已關閉。 第一個UIView使用AutoLayout來容納自身,但第二個UIView則不使用第二個UIView中的組件進行布局。
觀察:
如果將背景色添加到第二個UIView時將其添加到容器UIView中,則框架非常合適,但是組件不完美,它們總是看起來不對。 我嘗試過clipToBounds = true
,它通過將組件保留在UIView中來工作,但是我找不到將所有組件(UITextField,UIButton等)與兩個UIView對齊的方法。
屏幕截圖:
容器/第一個UIView的代碼:
override func viewDidAppear(animated: Bool)
{
super.viewDidAppear(animated)
// loginView = IS THE UIView in the second NIB.
// otherViews = IS THE UIView CONTAINER in the first NIB.
let loginView = BCAKLoginView() // LOAD NIB FILE
self.loginView.frame = self.otherViews.bounds
self.loginView.hidden = false
self.loginView.backgroundColor = UIColor.redColor()
self.loginView.clipsToBounds = true
self.otherViews.addSubview(loginView) // HERE I ADD THE SECOND NIB TO UIView.
let constraintLeading = NSLayoutConstraint.init(
item: self.loginView,
attribute: NSLayoutAttribute.Leading,
relatedBy: NSLayoutRelation.Equal,
toItem: self.otherViews,
attribute: NSLayoutAttribute.Leading,
multiplier: 1.0,
constant: 0.0
)
let constraintWidth = NSLayoutConstraint.init(
item: self.loginView,
attribute: NSLayoutAttribute.Width,
relatedBy: NSLayoutRelation.Equal,
toItem: self.otherViews,
attribute: NSLayoutAttribute.Width,
multiplier: 1.0,
constant: 0.0
)
let constraintTop = NSLayoutConstraint.init(
item: self.loginView,
attribute: NSLayoutAttribute.Top,
relatedBy: NSLayoutRelation.Equal,
toItem: self.otherViews,
attribute: NSLayoutAttribute.Top,
multiplier: 1.0,
constant: 0.0
)
let constraintBottom = NSLayoutConstraint.init(
item: self.loginView,
attribute: NSLayoutAttribute.Bottom,
relatedBy: NSLayoutRelation.Equal,
toItem: self.otherViews,
attribute: NSLayoutAttribute.Bottom,
multiplier: 1.0,
constant: 0.0
)
self.otherViews.addConstraint(constraintLeading)
self.otherViews.addConstraint(constraintWidth)
self.otherViews.addConstraint(constraintTop)
self.otherViews.addConstraint(constraintBottom)
}
好吧,回答我自己的問題..
問題是當我實例化第二個NIB文件(UIView)時。 在initWithFrame:
和initWithCoder:
。 我將其添加為自己的子視圖,因此在loginView
和otherViews
之間添加了一個額外的UIView。 就是這樣...當我刪除這個多余的視圖時,一切都對齊了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.