I'm trying to use a UIScrollView on my view as the content that I want to show won't fit on the screen. I work purely programmatically and cannot seem to grasp why my UIScrollView simply will not work when adding constraints. It works perfectly with frames but I that's the awkward, old way of doing things. I want to be able to add views to the scroll view and of course scroll down as it goes off screen. I have tried to add a topView as one of the views I want to be able to add and scroll with the scrollview but no joy. Where am I going wrong? Any help will be highly appreciated.
class ScrollTest: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
setupviews()
}
let topView: UIView = {
let view = UIView()
view.backgroundColor = .yellow
return view
}()
let containerView: UIView = {
let view = UIView()
view.backgroundColor = .white
return view
}()
let scrollView: UIScrollView = {
let sv = UIScrollView()
sv.backgroundColor = .white
sv.translatesAutoresizingMaskIntoConstraints = false
return sv
}()
func setupviews() {
view.addSubview(scrollView)
scrollView.addSubview(containerView)
containerView.addSubview(topView)
scrollView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
scrollView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
//
_ = containerView.anchor(scrollView.topAnchor, left: scrollView.leftAnchor, bottom: scrollView.bottomAnchor, right: scrollView.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 700)
_ = topView.anchor(view.topAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, topConstant: 100, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 50)
}
}