将子视图布局锚点设置为 UIScrollView



当我想在UIScrollView中设置子视图的顶部锚点时,我必须给它们一个恒定的高度,否则scrollView将无法滚动。但随着他们数量的增加,感觉就像一团糟。

例如,如果我将第二个子视图的topAnchor设置为第一个子视图的bottomAnchor,它不会滚动。我必须将它们设置为滚动视图的锚点。 有没有更好的方法来实现这一目标,而无需给出常数并自己计算距离?

这是我的滚动视图:

scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.contentSize = CGSize(width: UIScreen.main.bounds.width, height: 500)
scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
scrollView.isScrollEnabled = true
belowContainer.addSubview(scrollView)
scrollView.topAnchor.constraint(equalTo: belowContainer.topAnchor, constant: 20).isActive = true
scrollView.leadingAnchor.constraint(equalTo: belowContainer.leadingAnchor).isActive = true
scrollView.trailingAnchor.constraint(equalTo: belowContainer.trailingAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: belowContainer.bottomAnchor, constant: 0).isActive = true

我使用以下变量来正确设置子视图之间的垂直间距

var counter : CGFloat = 0; // height space counter between uiItems below!
let multiplierHeight : CGFloat = 32 // we multiply our counter by this value to get the right spacing!

最后,我让我的子视图锚定在一个 for 循环中,如下所示:

for lbl in labelsArray {
lbl.font = UIFont(name: fontName, size: 20)
lbl.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: counter * multiplierHeight).isActive = true          
lbl.heightAnchor.constraint(equalToConstant: 25).isActive = true
counter += 1
}

这似乎不是解决您问题的正确方法。相反,您应该级联标签,以便一个标签的底部约束链接到下一个标签的顶部约束。这样,您就不必执行顶部约束常量乘法。

但是,您可能需要考虑使用堆栈视图来实现您的目标。使用约束将堆栈视图固定到滚动视图的内容视图,然后使用for循环将标签添加到堆栈视图:

stackView.addArrangedSubview(lbl)

堆栈视图的优点是不需要单个布局约束。相反,堆栈视图本身负责定位其子视图。

最新更新