I have created a scrollView in code and added several labels to it:
private let scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.backgroundColor = .systemTeal
return scrollView
}()
In viewDidLoad:
view.addSubview(scrollView)
[view1, label1, label2, label3, label4, label5].forEach { scrollView.addSubview($0) }
setViewContraints()
Then in 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. Every view's trailing and leading anchors are anchored to the scrollview's trailing and leading anchors. This is done in setViewConstraints().
view.width and view.height return view.frame.size.width and view.frame.size.height respectively.
All the content appears fine but the scrollView doesn't work. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.