1

我需要以编程方式将 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
}
4

0 回答 0