我在将约束添加到新实例化的 UIView 从 NIB 到另一个 UIView(另一个 NIB 的一部分)时遇到问题。
我真正想做的是:
- 从 NIB 文件加载 UIView。 (完成)
- 在第一个 NIB 文件中有一个 UIView 组件,充当另一个 UIView 的容器。灰色背景。 (完成)
- 从另一个 NIB 文件加载第二个 UIView(绿色背景)并将其放置在第一个 UIView(灰色背景)中。 (问题就在这里)我所说的里面正是在容器的位置。容器 UIView 是 300x280(灰色背景),外部 UIView 也是 300x280(绿色背景)。
我可以在第一个 UIView 中添加第二个 UIView,因为我可以看到它,但约束已关闭。第一个 UIView 使用 AutoLayout 来适应自身,但第二个 UIView 则不然,第二个 UIView 中的组件是使用 IB 进行布局的。
观察:
如果我在将第二个 UIView 添加到容器 UIView 时为其添加背景颜色,则框架完美适合,但组件不适合,它们总是看起来不合适。我已经尝试过clipToBounds = true
它的工作原理是将组件保留在 UIView 内,但我找不到将所有组件(UITextFields、UIButtons 等)与两个 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:
中。我将其添加为自己的 subview ,因此在 loginView
和 otherViews
之间添加了一个额外的 UIView。就是这样...当我删除这个额外的 View 时,一切都自行对齐。
关于ios - 将实例化的 UIView 从 NIB 约束到其他 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33550087/