当我想在 a 中设置我的子视图的顶部锚点时UIScrollView
,我必须给它们一个恒定的高度,否则 scrollView 不会滚动。但随着他们数量的增加,感觉就像一团糟。
例如,如果我将我的 2nd subviews' 设置topAnchor
为 first one's 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
}