我需要以编程方式将nib文件加载到滚动视图中,并且需要固定约束来滚动视图。我的观点很复杂所以我决定使用Nib,但必须在滚动视图中以编程方式添加它们。我尝试了几乎所有的方法,但约束似乎没有起作用。请参阅下面的代码。
1)创建滚动视图并添加约束:
scrollView.snp.makeConstraints { (make) in
make.edges.equalTo(view)
make.centerY.equalToSuperview()
}
2)将内容视图添加到滚动视图中:
contentView = UIView()
contentView.backgroundColor = .red
scrollView.addSubview(contentView)
contentView.snp.makeConstraints { (make) in
make.edges.equalTo(scrollView)
make.size.height.equalTo(scrollView)
make.centerY.equalToSuperview()
}
3)加载Nib视图并将其添加到内容视图中。这里的技巧是将第一个视图宽度设置为滚动视图,以便它自动调整大小到每个视图大小并使所有子视图等于宽度:
var previous: customView = customView()
// suppose we have three custom views need to loaded from Nib and add in scroll view
for i in 0..<3 {
let view = customView() // Tried giving frame as well but no success
view.initWithTitle(tutorailArray![i].heading, title: tutorailArray![i].title, image: tutorailArray![i].imageName)
self.contentView.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
view.snp.makeConstraints({ [weak contentView, previous, scrollView] (make) in
make.top.bottom.equalTo(contentView!)
if ( i == 0) {
make.size.width.equalTo(scrollView)
make.leading.equalTo(contentView!)
}
else {
make.size.width.equalTo(previous)
make.leading.equalTo(previous)
}
if i == 2 {
make.size.width.equalTo(previous)
make.trailing.equalTo(contentView!)
make.leading.equalTo(previous)
}
})
previous = view
}