0

当我想在 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
    }
4

1 回答 1

1

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

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

stackView.addArrangedSubview(lbl)

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

于 2018-06-08T06:21:56.033 回答