根据contenView的大小以编程方式调整scrollView的大小[Swift]

问题描述 投票:0回答:1

在我的应用中,我尝试根据内容创建自动调整大小的滚动视图,这是我的意思的简化版本。我知道我应该使用contentView,但是这样做不起作用!

    view.addSubview(mainScrollView)
    mainScrollView.addSubview(contentView)

    mainScrollView.anchorFor(superview: view) // .zero to all edges of view

    let view1 = UIView(frame: view.frame)
    view1.backgroundColor = .red

    let view2 = UIView(frame: view.frame)
    view2.backgroundColor = .brown
    view2.frame.origin.y = view1.frame.height

    mainScrollView.contentSize.height = 2 * view.frame.height

现在,如果我不指定contentSize,则只会显示红色视图。我也尝试过这种方式:

    let contentView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height))
    contentView.translatesAutoresizingMaskIntoConstraints = false
    contentView.backgroundColor = .black

    contentView.fillSuperview() // .zero to scrollview edges, but it doesn't work
        .
        .
        .
    contentView.addSubviews(view1,view2)

我如何根据可以更改的contentView大小来调整scoll视图的大小,例如,通过单击按钮“展开”,全部以编程方式没有情节提要。谢谢

swift view uiscrollview
1个回答
0
投票

添加全部subview后,需要使用以下代码计算contentSize

let contentRect: CGRect = scrollView.subviews.reduce(into: .zero) { rect, view in
    rect = rect.union(view.frame)
}
scrollView.contentSize = contentRect.size

注意:

如果您的subview动态添加和删除,那么不要忘记调用它。

© www.soinside.com 2019 - 2024. All rights reserved.