UIViewController 内部的 UIScrollView 不水平滚动

UIScrollView inside of UIViewController not scrolling horizontally

我在 UIViewController 中创建了一个 UIScrollView。我在我的 UIScrollView 中添加了一个 UIView,在 UIView 中有一个标签。计划是最终添加 3 个非常大的 UIButton,这就是我需要滚动视图的原因。我没有使用故事板,它全部以编程方式完成。我无法让 UIScrollView 工作。

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)
}

您需要确保滚动视图的宽度 contentSize 大于滚动视图本身的宽度。像下面这样简单的事情应该会导致水平滚动发生:

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