简体   繁体   English

iOS:程序化 ScrollView 不滚动(contentSize 设置)

[英]iOS: Programatic ScrollView not scrolling (contentSize set)

I have created a scrollView in code and added several labels to it:我在代码中创建了一个 scrollView 并向其中添加了几个标签:

private let scrollView: UIScrollView = {
    let scrollView = UIScrollView()
    scrollView.backgroundColor = .systemTeal
    return scrollView
}()

In viewDidLoad:在 viewDidLoad 中:

view.addSubview(scrollView)
[view1, label1, label2, label3, label4, label5].forEach { scrollView.addSubview($0) }

setViewContraints()

Then in viewDidLayoutSubviews:然后在 viewDidLayoutSubviews 中:

override func viewDidLayoutSubviews() {
    scrollView.frame = view.bounds
    scrollView.contentSize = CGSize(width: view.width, height: view.height + 300)
}

The first view is anchored to the scrollview safeAreaLayoutGuide topAnchor, then each subsequent label's topAnchor is anchored to the bottom of the previous bottomAnchor.第一个视图锚定到scrollview safeAreaLayoutGuide topAnchor,然后每个后续标签的topAnchor 锚定到前一个bottomAnchor 的底部。 Every view's trailing and leading anchors are anchored to the scrollview's trailing and leading anchors.每个视图的尾随和前导锚点都锚定到滚动视图的尾随和前导锚点。 This is done in setViewConstraints().这是在 setViewConstraints() 中完成的。

view.width and view.height return view.frame.size.width and view.frame.size.height respectively. view.width 和 view.height 分别返回 view.frame.size.width 和 view.frame.size.height。

All the content appears fine but the scrollView doesn't work.所有内容看起来都很好,但 scrollView 不起作用。 What am I doing wrong?我究竟做错了什么?

I realized I needed to set the bottomAnchor of my bottom-most view to the bottom anchor of the scroll view.我意识到我需要将最底部视图的底部锚点设置为滚动视图的底部锚点。 That did the trick.那成功了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM