【发布时间】:2017-06-15 20:11:17
【问题描述】:
我正在尝试在 swift iOS 10 中的 xib/nib 文件中创建可重用视图。
当我创建一个堆栈视图并在其中包含 2 个对象并确保我的堆栈视图被限制在 nib/xib 的容器视图中时(从上到上,从下到下,导致前导,最后尾随到尾随),我收到一条错误消息,提示我缺少第一个和第二个对象的 Y 位置。只创建其中一个通常可以修复它。虽然这是横盘整理的地方。在我之前的所有研究中,如果我将我的 stackview 分发到 Fill,我不应该这样做。尽管这似乎使 Xcode 安静下来,但当我尝试运行我的程序时,它会产生过度约束问题。
这是我用来在我的主故事板视图中加载我的笔尖的内容:
public protocol NibOwnerLoadable: class {
static var nib: UINib { get }
}
//MARK:- Generic Implementation
public extension NibOwnerLoadable {
// Use the xib file with the same name as your UIView subclass located in the bundle of that class
static var nib: UINib {
return UINib(nibName: String(describing: self), bundle: Bundle(for: self))
}
}
//MARK:- Support for instation from the XIB file
public extension NibOwnerLoadable where Self: UIView {
// Function to load content and constraints automatically
func loadNibContent() {
let layoutAttributes: [NSLayoutAttribute] = [.top, .leading, .bottom, .trailing]
for view in Self.nib.instantiate(withOwner: self, options: nil) {
if let view = view as? UIView {
view.translatesAutoresizingMaskIntoConstraints = false
view.frame = bounds
self.addSubview(view)
layoutAttributes.forEach{ attribute in self.addConstraint(NSLayoutConstraint(item: view, attribute: attribute, relatedBy: .equal, toItem: self, attribute: attribute, multiplier: 1, constant: 0.0))
}
}
}
}
}
我知道我的问题是自动布局添加了一个额外的约束,但是为什么以及在哪里。另一个问题与我想要做的非常接近,但由于某种原因,我的 AutoLayout 知识在我脑海中一团糟。 Adding a subclassed UIView to a Nib with its auto layout constraints 一点帮助将不胜感激。请解释原因,而不仅仅是如何去做。我是一个喜欢了解背后故事的人。它使它合乎逻辑且更容易保留。
以下是我的 filterView 作为 nib/xib 加载到 searchAndFilterView 作为 FilterView (UIView) 的图片,它加载到我的故事板中的一个视图控制器中。考虑可重用的工具视图。
【问题讨论】:
-
让我再澄清一点...
-
先看看我能不能完成这个任务。我希望我的 XIB/NIB 视图的容器视图具有一定的高度。这些 XIB/NIB 视图必须具有一定的大小,并且必须位于堆栈视图中,这样当该容器视图被隐藏时,我可以为视图收缩设置动画。我可以在没有 XIB/NIB 的情况下执行此操作,但我无法使用我的 XIB/NIB fileOwner 的子类的容器视图来完成此操作。
标签: xib nslayoutconstraint nib ios-autolayout