这是通过for循环在滚动视图中显示图像视图的方式:
func addPageController() {
let imgArray = ["AquariumBG","PaludariumBG","TerrariumBG"]
let scrollContentViewWidthAnchor = scrollContentView.widthAnchor.constraint(equalTo: headerScrollView.widthAnchor,constant:0)
scrollContentViewWidthAnchor.isactive = true
for (index,item) in imgArray.enumerated() {
let imgView = UIImageView()
imgView.contentMode = .scaleAspectFill
imgView.image = UIImage(named: item)
let xPos = CGFloat(index) * UIScreen.main.bounds.size.width
scrollContentView.addSubview(imgView)
scrollContentView.translatesAutoresizingMaskintoConstraints = false
scrollContentView.topAnchor.constraint(equalTo: headerScrollView.topAnchor,constant: 0).isactive = true
scrollContentView.bottomAnchor.constraint(equalTo: headerScrollView.bottomAnchor,constant: 0).isactive = true
scrollContentView.leadingAnchor.constraint(equalTo: headerScrollView.leadingAnchor,constant: 0).isactive = true
scrollContentViewWidthAnchor.constant = xPos
scrollContentView.setNeedsLayout()
scrollContentView.layoutIfNeeded()
imgView.translatesAutoresizingMaskintoConstraints = false
imgView.topAnchor.constraint(equalTo: scrollContentView.topAnchor,constant: 0).isactive = true
imgView.bottomAnchor.constraint(equalTo: scrollContentView.bottomAnchor,constant: 0).isactive = true
imgView.widthAnchor.constraint(equalToConstant: headerScrollView.frame.size.width).isactive = true
imgView.leadingAnchor.constraint(equalTo: scrollContentView.leadingAnchor,constant: xPos).isactive = true
imgView.widthAnchor.constraint(equalToConstant: headerScrollView.frame.size.width).isactive = true
imgView.setNeedsLayout()
imgView.layoutIfNeeded()
}
}
这是输出:
显示完美。现在,如果我将页眉向下滑动到屏幕上(因为它是可伸缩的页眉),则第二张图像也会与第一张图像一起显示,如下所示:
其原因是因为图像视图没有trailingAnchor.constraint
。所以我的问题是,当尚未创建下一个图像视图时,是否可以在循环内设置带有图像视图的尾锚?如果可以,怎么办?任何建议将不胜感激。预先感谢。
我的故事板: