0
votes

I am trying to create a Scroll View. The view itself is correctly displayed but it does not scroll, even though I added a view to it and set the content size.

NOTE: I am not using storyboards but Constraints (AutoLayout) only.

Code:

let scrollView: UIScrollView = {
        let sv = UIScrollView()
        sv.isScrollEnabled = true
        sv.backgroundColor = .brown
        return sv
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        setupViews()
    }

    func setupViews() {
        self.view.addSubview(scrollView)
        scrollView.anchor(top: self.view.topAnchor, left: self.view.leftAnchor, bottom: self.view.bottomAnchor, right: self.view.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
        scrollView.contentSize = CGSize(width: self.view.frame.width, height: 2000)

        print(scrollView.contentSize)

        let view = UIView()
        view.backgroundColor = .blue


        scrollView.addSubview(view)

        view.anchor(top: scrollView.topAnchor, left: scrollView.leftAnchor, bottom: scrollView.bottomAnchor, right: scrollView.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
    }

.anchor() is a custom extension I made in order to make constraining views easier.

Any help would be appreciated.

1
Your view is the size of the entire scroll viewNathan

1 Answers

1
votes

It's better not to mix autolayout with frame layout do

1- Comment

scrollView.contentSize = CGSize(width: self.view.frame.width, height: 2000)

2- set equal width constraint between the view inside the scrollview to the vc's view and a height constraint of 2000

For no confuse with vc's view change

let view = UIView()

to

let contentView = UIView()

then add these 2 constarints

contentView.widthAnchor.constraint(equalTo:self.view.widthAnchor).isActive = true
contentView.heightAnchor.constraint(equalToConstant:2000).isActive = true