0
votes

I have created a UIScrollView inside of a UIViewController. I have added a UIView inside of my UIScrollView with one label inside of the UIView. The plan is to eventually add 3 very large UIButtons that is why I need a scroll view. I have not used storyboard and it is done all programmatically. I cannot get the UIScrollView to work.

class ChooseCategoryPostViewController: UIViewController, UIScrollViewDelegate {

       let scrollView: UIScrollView = {
       let sv = UIScrollView()
       sv.backgroundColor = .green
       return sv
                     }()

       let myView: UIView = {
       let view = UIView()
       view.backgroundColor = .red
       return view
                    }()

       let test: UILabel = {
          let label = UILabel()
          label.text = "test label"
          label.font = UIFont.boldSystemFont(ofSize: 15)
          label.textAlignment = .center
          return label
      }()


         override func viewDidLoad() {
    view.addSubview(scrollView)
    scrollView.addSubview(myView)
    
    scrollView.anchor(top: topTitle.bottomAnchor, left: nil, bottom: nil, right: nil, paddingTop: 200, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: view.frame.width, height: 200)
    myView.anchor(top: scrollView.topAnchor, left: scrollView.leftAnchor, bottom: scrollView.bottomAnchor, right: nil, paddingTop: 0, paddingLeft: 10, paddingBottom: 0, paddingRight: 0, width: 1700, height: 200)
    myView.addSubview(test)
    test.anchor(top: myView.topAnchor, left: nil, bottom: nil, right: myView.rightAnchor, paddingTop: 20, paddingLeft: 0, paddingBottom: 0, paddingRight: 20, width: 0, height: 0)

}

 override func viewDidLayoutSubviews() {
    scrollView.isScrollEnabled = true
    // Do any additional setup after loading the view
    scrollView.contentSize = CGSize(width: view.frame.width, height: 200)
}
1
You maybe can add an Horizontal StackView inside your ScrollView. And then add your labels and buttons inside the StackViewdieroste
I tried that it still won't scroll.soRazor
Did you double check what view.frame.width is when you set the scroll view's content size? If you're using programmatic auto layout, I believe setting constraints on the scroll view's contentLayoutGuide is the way to go, and I'm not sure the non-standard anchor function that is being used here does this.Dirty Henry
This is because your content size width is less than or equal to the width of the scroll view. You need to make the content size width greater than the scroll view widthNoodleOfDeath

1 Answers

0
votes

You need to make sure that the width of the scroll view contentSize is greater than the width of the scroll view itself. Something as simple as the following should cause horizontal scrolling to happen:

override func viewDidLayoutSubviews() {
    scrollView.isScrollEnabled = true
    // Do any additional setup after loading the view
    scrollView.contentSize = CGSize(width: view.frame.width * 2, height: 200)
}